<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>OAuth 2.0 Client :: Spring Security</title>
<link rel="canonical" href="oauth2-client.html">
<link rel="prev" href="oauth2-login.html">
<link rel="next" href="oauth2-resourceserver.html">
<meta name="generator" content="Antora 3.0.0">
<link rel="stylesheet" href="../../../_/css/site.css">
<link href="../../../_/img/favicon.ico" rel='shortcut icon' type='image/vnd.microsoft.icon'>
<link rel="stylesheet" href="../../../_/css/vendor/docsearch.min.css">

<script>var uiRootPath = '../../../_'</script>
</head>
<body class="article">
<header class="header">
<nav class="navbar">
<div class="navbar-brand">
<a class="navbar-item" href="https://spring.io">
<img id="springlogo" class="block" src="../../../_/img/spring-logo.svg" alt="Spring">
</a>
<button class="navbar-burger" data-target="topbar-nav">
<span></span>
<span></span>
<span></span>
</button>
</div>
<div id="topbar-nav" class="navbar-menu">
<div class="navbar-end">
<div class="navbar-item has-dropdown is-hoverable">
<a class="navbar-link" href="oauth2-client.html#">Why Spring</a>
<div class="navbar-dropdown">
<a class="navbar-item" href="https://spring.io/why-spring">Overview</a>
<a class="navbar-item" href="https://spring.io/microservices">Microservices</a>
<a class="navbar-item" href="https://spring.io/reactive">Reactive</a>
<a class="navbar-item" href="https://spring.io/event-driven">Event Driven</a>
<a class="navbar-item" href="https://spring.io/cloud">Cloud</a>
<a class="navbar-item" href="https://spring.io/web-applications">Web Applications</a>
<a class="navbar-item" href="https://spring.io/serverless">Serverless</a>
<a class="navbar-item" href="https://spring.io/batch">Batch</a>
</div>
</div>
<div class="navbar-item has-dropdown is-hoverable">
<a class="navbar-link" href="oauth2-client.html#">Learn</a>
<div class="navbar-dropdown">
<a class="navbar-item" href="https://spring.io/learn">Overview</a>
<a class="navbar-item" href="https://spring.io/quickstart">Quickstart</a>
<a class="navbar-item" href="https://spring.io/guides">Guides</a>
<a class="navbar-item" href="https://spring.io/blog">Blog</a>
</div>
</div>
<div class="navbar-item has-dropdown is-hoverable">
<a class="navbar-link" href="oauth2-client.html#">Projects</a>
<div class="navbar-dropdown">
<a class="navbar-item" href="https://spring.io/projects">Overview</a>
<a class="navbar-item" href="https://spring.io/projects/spring-boot">Spring Boot</a>
<a class="navbar-item" href="https://spring.io/projects/spring-framework">Spring Framework</a>
<a class="navbar-item" href="https://spring.io/projects/spring-cloud">Spring Cloud</a>
<a class="navbar-item" href="https://spring.io/projects/spring-cloud-dataflow">Spring Cloud Data Flow</a>
<a class="navbar-item" href="https://spring.io/projects/spring-data">Spring Data</a>
<a class="navbar-item" href="https://spring.io/projects/spring-integration">Spring Integration</a>
<a class="navbar-item" href="https://spring.io/projects/spring-batch">Spring Batch</a>
<a class="navbar-item" href="https://spring.io/projects/spring-security">Spring Security</a>
<a class="navbar-item navbar-item-special" href="https://spring.io/projects">View all projects</a>
<a class="navbar-item" href="https://spring.io/tools">Spring Tools 4</a>
<a class="navbar-item navbar-item-special-2" href="https://start.spring.io">Spring Initializr <svg class="external-link-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><polyline points="15 10.94 15 15 1 15 1 1 5.06 1" fill="none" stroke="currentColor" stroke-miterlimit="10" stroke-width="2"></polyline><polyline points="8.93 1 15 1 15 7.07" fill="none" stroke="currentColor" stroke-miterlimit="10" stroke-width="2"></polyline><line x1="15" y1="1" x2="8" y2="8" fill="none" stroke="currentColor" stroke-miterlimit="10" stroke-width="2"></line></svg></a>
</div>
</div>
<a class="navbar-item" href="https://spring.io/training">Training</a>
<a class="navbar-item" href="https://spring.io/support">Support</a>
<div class="navbar-item has-dropdown is-hoverable is-community">
<a class="navbar-link" href="oauth2-client.html#">Community</a>
<div class="navbar-dropdown">
<a class="navbar-item" href="https://spring.io/community">Overview</a>
<a class="navbar-item" href="https://spring.io/events">Events</a>
<a class="navbar-item" href="https://spring.io/team">Team</a>
</div>
</div>
</div>
</div>
<div id="switch-theme">
<input type="checkbox" id="switch-theme-checkbox" />
<label for="switch-theme-checkbox">Dark Theme</label>
</div>
</nav>
</header>
<div class="body">
<div class="nav-container" data-component="ROOT" data-version="5.6.0-RC1">
<aside class="nav">
<div class="panels">
<div class="nav-panel-menu is-active" data-panel="menu">
<nav class="nav-menu">
<h3 class="title"><a href="../../index.html">Spring Security</a></h3>
<ul class="nav-list">
<li class="nav-item" data-depth="0">
<ul class="nav-list">
<li class="nav-item" data-depth="1">
<a class="nav-link" href="../../index.html">Overview</a>
</li>
<li class="nav-item" data-depth="1">
<a class="nav-link" href="../../prerequisites.html">Prerequisites</a>
</li>
<li class="nav-item" data-depth="1">
<a class="nav-link" href="../../community.html">Community</a>
</li>
<li class="nav-item" data-depth="1">
<a class="nav-link" href="../../whats-new.html">What&#8217;s New</a>
</li>
<li class="nav-item" data-depth="1">
<a class="nav-link" href="../../getting-spring-security.html">Getting Spring Security</a>
</li>
<li class="nav-item" data-depth="1">
<button class="nav-item-toggle"></button>
<a class="nav-link" href="../../features/index.html">Features</a>
<ul class="nav-list">
<li class="nav-item" data-depth="2">
<button class="nav-item-toggle"></button>
<a class="nav-link" href="../../features/authentication/index.html">Authentication</a>
<ul class="nav-list">
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../../features/authentication/password-storage.html">Password Storage</a>
</li>
</ul>
</li>
<li class="nav-item" data-depth="2">
<button class="nav-item-toggle"></button>
<a class="nav-link" href="../../features/exploits/index.html">Protection Against Exploits</a>
<ul class="nav-list">
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../../features/exploits/csrf.html">CSRF</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../../features/exploits/headers.html">HTTP Headers</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../../features/exploits/http.html">HTTP Requests</a>
</li>
</ul>
</li>
<li class="nav-item" data-depth="2">
<button class="nav-item-toggle"></button>
<a class="nav-link" href="../../features/integrations/index.html">Integrations</a>
<ul class="nav-list">
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../../features/integrations/cryptography.html">Cryptography</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../../features/integrations/data.html">Spring Data</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../../features/integrations/concurrency.html">Java&#8217;s Concurrency APIs</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../../features/integrations/jackson.html">Jackson</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../../features/integrations/localization.html">Localization</a>
</li>
</ul>
</li>
</ul>
</li>
<li class="nav-item" data-depth="1">
<a class="nav-link" href="../../modules.html">Project Modules</a>
</li>
<li class="nav-item" data-depth="1">
<a class="nav-link" href="../../samples.html">Samples</a>
</li>
<li class="nav-item" data-depth="1">
<button class="nav-item-toggle"></button>
<a class="nav-link" href="../index.html">Servlet Applications</a>
<ul class="nav-list">
<li class="nav-item" data-depth="2">
<a class="nav-link" href="../getting-started.html">Getting Started</a>
</li>
<li class="nav-item" data-depth="2">
<a class="nav-link" href="../architecture.html">Architecture</a>
</li>
<li class="nav-item" data-depth="2">
<button class="nav-item-toggle"></button>
<a class="nav-link" href="../authentication/index.html">Authentication</a>
<ul class="nav-list">
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../authentication/architecture.html">Authentication Architecture</a>
</li>
<li class="nav-item" data-depth="3">
<button class="nav-item-toggle"></button>
<a class="nav-link" href="../authentication/passwords/index.html">Username/Password</a>
<ul class="nav-list">
<li class="nav-item" data-depth="4">
<button class="nav-item-toggle"></button>
<span class="nav-text">Reading Username/Password</span>
<ul class="nav-list">
<li class="nav-item" data-depth="5">
<a class="nav-link" href="../authentication/passwords/form.html">Form</a>
</li>
<li class="nav-item" data-depth="5">
<a class="nav-link" href="../authentication/passwords/basic.html">Basic</a>
</li>
<li class="nav-item" data-depth="5">
<a class="nav-link" href="../authentication/passwords/digest.html">Digest</a>
</li>
</ul>
</li>
<li class="nav-item" data-depth="4">
<button class="nav-item-toggle"></button>
<span class="nav-text">Password Storage</span>
<ul class="nav-list">
<li class="nav-item" data-depth="5">
<a class="nav-link" href="../authentication/passwords/in-memory.html">In Memory</a>
</li>
<li class="nav-item" data-depth="5">
<a class="nav-link" href="../authentication/passwords/jdbc.html">JDBC</a>
</li>
<li class="nav-item" data-depth="5">
<a class="nav-link" href="../authentication/passwords/user-details.html">UserDetails</a>
</li>
<li class="nav-item" data-depth="5">
<a class="nav-link" href="../authentication/passwords/user-details-service.html">UserDetailsService</a>
</li>
<li class="nav-item" data-depth="5">
<a class="nav-link" href="../authentication/passwords/password-encoder.html">PasswordEncoder</a>
</li>
<li class="nav-item" data-depth="5">
<a class="nav-link" href="../authentication/passwords/dao-authentication-provider.html">DaoAuthenticationProvider</a>
</li>
<li class="nav-item" data-depth="5">
<a class="nav-link" href="../authentication/passwords/ldap.html">LDAP</a>
</li>
</ul>
</li>
</ul>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../authentication/session-management.html">Session Management</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../authentication/rememberme.html">Remember Me</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../authentication/openid.html">OpenID</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../authentication/anonymous.html">Anonymous</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../authentication/preauth.html">Pre-Authentication</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../authentication/jaas.html">JAAS</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../authentication/cas.html">CAS</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../authentication/x509.html">X509</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../authentication/runas.html">Run-As</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../authentication/logout.html">Logout</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../authentication/events.html">Authentication Events</a>
</li>
</ul>
</li>
<li class="nav-item" data-depth="2">
<button class="nav-item-toggle"></button>
<a class="nav-link" href="../authorization/index.html">Authorization</a>
<ul class="nav-list">
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../authorization/architecture.html">Authorization Architecture</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../authorization/authorize-requests.html">Authorize HTTP Requests</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../authorization/expression-based.html">Expression-Based Access Control</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../authorization/secure-objects.html">Secure Object Implementations</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../authorization/method-security.html">Method Security</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../authorization/acls.html">Domain Object Security ACLs</a>
</li>
</ul>
</li>
<li class="nav-item" data-depth="2">
<button class="nav-item-toggle"></button>
<a class="nav-link" href="index.html">OAuth2</a>
<ul class="nav-list">
<li class="nav-item" data-depth="3">
<a class="nav-link" href="oauth2-login.html">OAuth2 Log In</a>
</li>
<li class="nav-item is-current-page" data-depth="3">
<a class="nav-link" href="oauth2-client.html">OAuth2 Client</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="oauth2-resourceserver.html">OAuth2 Resource Server</a>
</li>
</ul>
</li>
<li class="nav-item" data-depth="2">
<a class="nav-link" href="../saml2/index.html">SAML2</a>
</li>
<li class="nav-item" data-depth="2">
<button class="nav-item-toggle"></button>
<a class="nav-link" href="../exploits/index.html">Protection Against Exploits</a>
<ul class="nav-list">
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../exploits/csrf.html">Cross Site Request Forgery (CSRF) for Servlet Environments</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../exploits/headers.html">Security HTTP Response Headers</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../exploits/http.html">HTTP</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../exploits/firewall.html">HttpFirewall</a>
</li>
</ul>
</li>
<li class="nav-item" data-depth="2">
<button class="nav-item-toggle"></button>
<a class="nav-link" href="../integrations/index.html">Integrations</a>
<ul class="nav-list">
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../integrations/servlet-api.html">Servlet APIs</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../integrations/mvc.html">Spring MVC</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../integrations/websocket.html">WebSocket</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../integrations/cors.html">Spring&#8217;s CORS Support</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../integrations/jsp-taglibs.html">JSP Taglib</a>
</li>
</ul>
</li>
<li class="nav-item" data-depth="2">
<button class="nav-item-toggle"></button>
<span class="nav-text">Configuration</span>
<ul class="nav-list">
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../configuration/java.html">Java Configuration</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../configuration/kotlin.html">Kotlin Configuration</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../configuration/xml-namespace.html">Namespace Configuration</a>
</li>
</ul>
</li>
<li class="nav-item" data-depth="2">
<button class="nav-item-toggle"></button>
<a class="nav-link" href="../test/index.html">Testing</a>
<ul class="nav-list">
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../test/method.html">Method Security</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../test/mockmvc.html">MockMvc Support</a>
</li>
</ul>
</li>
<li class="nav-item" data-depth="2">
<button class="nav-item-toggle"></button>
<a class="nav-link" href="../appendix/index.html">Appendix</a>
<ul class="nav-list">
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../appendix/database-schema.html">Database Schemas</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../appendix/namespace.html">XML Namespace</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../appendix/faq.html">FAQ</a>
</li>
</ul>
</li>
</ul>
</li>
<li class="nav-item" data-depth="1">
<button class="nav-item-toggle"></button>
<a class="nav-link" href="../../reactive/index.html">Reactive Applications</a>
<ul class="nav-list">
<li class="nav-item" data-depth="2">
<a class="nav-link" href="../../reactive/getting-started.html">Getting Started</a>
</li>
<li class="nav-item" data-depth="2">
<button class="nav-item-toggle"></button>
<span class="nav-text">Authentication</span>
<ul class="nav-list">
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../../reactive/authentication/x509.html">X.509 Authentication</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../../reactive/authentication/logout.html">Logout</a>
</li>
</ul>
</li>
<li class="nav-item" data-depth="2">
<button class="nav-item-toggle"></button>
<span class="nav-text">Authorization</span>
<ul class="nav-list">
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../../reactive/authorization/method.html">EnableReactiveMethodSecurity</a>
</li>
</ul>
</li>
<li class="nav-item" data-depth="2">
<button class="nav-item-toggle"></button>
<a class="nav-link" href="../../reactive/oauth2/index.html">OAuth2</a>
<ul class="nav-list">
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../../reactive/oauth2/login.html">OAuth 2.0 Login</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../../reactive/oauth2/oauth2-client.html">OAuth2 Client</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../../reactive/oauth2/resource-server.html">OAuth 2.0 Resource Server</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../../reactive/registered-oauth2-authorized-client.html">@RegisteredOAuth2AuthorizedClient</a>
</li>
</ul>
</li>
<li class="nav-item" data-depth="2">
<button class="nav-item-toggle"></button>
<a class="nav-link" href="../../reactive/exploits/index.html">Protection Against Exploits</a>
<ul class="nav-list">
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../../reactive/exploits/csrf.html">CSRF</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../../reactive/exploits/headers.html">Headers</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../../reactive/exploits/http.html">HTTP Requests</a>
</li>
</ul>
</li>
<li class="nav-item" data-depth="2">
<button class="nav-item-toggle"></button>
<span class="nav-text">Integrations</span>
<ul class="nav-list">
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../../reactive/integrations/cors.html">CORS</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../../reactive/integrations/rsocket.html">RSocket</a>
</li>
<li class="nav-item" data-depth="3">
<a class="nav-link" href="../../reactive/integrations/webclient.html">WebClient</a>
</li>
</ul>
</li>
<li class="nav-item" data-depth="2">
<a class="nav-link" href="../../reactive/test.html">Testing</a>
</li>
<li class="nav-item" data-depth="2">
<a class="nav-link" href="../../reactive/configuration/webflux.html">WebFlux Security</a>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</nav>
</div>
<div class="nav-panel-explore" data-panel="explore">
<div class="context">
<span class="title">Spring Security</span>
<span class="version">5.6.0-RC1</span>
</div>
<ul class="components">
<li class="component is-current">
<a class="title" href="../../../index.html">Spring Security</a>
<ul class="versions">
<li class="version">
<a href="../../../6.0/index.html">6.0.0-SNAPSHOT</a>
</li>
<li class="version">
<a href="../../../6.0.0-M3/index.html">6.0.0-M3</a>
</li>
<li class="version">
<a href="../../../6.0.0-M2/index.html">6.0.0-M2</a>
</li>
<li class="version">
<a href="../../../6.0.0-M1/index.html">6.0.0-M1</a>
</li>
<li class="version">
<a href="../../../5.7/index.html">5.7.0-SNAPSHOT</a>
</li>
<li class="version">
<a href="../../../5.7.0-RC1/index.html">5.7.0-RC1</a>
</li>
<li class="version">
<a href="../../../5.7.0-M3/index.html">5.7.0-M3</a>
</li>
<li class="version">
<a href="../../../5.7.0-M2/index.html">5.7.0-M2</a>
</li>
<li class="version">
<a href="../../../5.7.0-M1/index.html">5.7.0-M1</a>
</li>
<li class="version">
<a href="../../../5.6.4/index.html">5.6.4-SNAPSHOT</a>
</li>
<li class="version is-latest">
<a href="../../../index.html">5.6.3</a>
</li>
<li class="version">
<a href="../../../5.6.2/index.html">5.6.2</a>
</li>
<li class="version">
<a href="../../../5.6.1/index.html">5.6.1</a>
</li>
<li class="version">
<a href="../../../5.6.0/index.html">5.6.0</a>
</li>
<li class="version is-current">
<a href="../../index.html">5.6.0-RC1</a>
</li>
</ul>
</li>
</ul>
</div>
</div>
</aside>
</div>
<main class="article">
<div class="toolbar" role="navigation">
<button class="nav-toggle"></button>
<nav class="breadcrumbs" aria-label="breadcrumbs">
<ul>
<li><a href="../../index.html">Spring Security</a></li>
<li><a href="../index.html">Servlet Applications</a></li>
<li><a href="index.html">OAuth2</a></li>
<li><a href="oauth2-client.html">OAuth2 Client</a></li>
</ul>
</nav>
<div class="search">
<input id="search-input" type="text" placeholder="Search docs">
</div>
<div class="page-versions">
<button class="version-menu-toggle" title="Show other versions of page">5.6.0-RC1</button>
<div class="version-menu">
<a class="version is-missing" href="../../../6.0/index.html">6.0.0-SNAPSHOT</a>
<a class="version is-missing" href="../../../6.0.0-M3/index.html">6.0.0-M3</a>
<a class="version is-missing" href="../../../6.0.0-M2/index.html">6.0.0-M2</a>
<a class="version is-missing" href="../../../6.0.0-M1/index.html">6.0.0-M1</a>
<a class="version is-missing" href="../../../5.7/index.html">5.7.0-SNAPSHOT</a>
<a class="version is-missing" href="../../../5.7.0-RC1/index.html">5.7.0-RC1</a>
<a class="version is-missing" href="../../../5.7.0-M3/index.html">5.7.0-M3</a>
<a class="version is-missing" href="../../../5.7.0-M2/index.html">5.7.0-M2</a>
<a class="version is-missing" href="../../../5.7.0-M1/index.html">5.7.0-M1</a>
<a class="version is-missing" href="../../../5.6.4/index.html">5.6.4-SNAPSHOT</a>
<a class="version is-missing" href="../../../index.html">5.6.3</a>
<a class="version is-missing" href="../../../5.6.2/index.html">5.6.2</a>
<a class="version is-missing" href="../../../5.6.1/index.html">5.6.1</a>
<a class="version is-missing" href="../../../5.6.0/index.html">5.6.0</a>
<a class="version is-current" href="oauth2-client.html">5.6.0-RC1</a>
</div>
</div>
<div class="edit-this-page"><a href="https://github.com/spring-projects/spring-security/blob/5.6.0-RC1/docs/modules/ROOT/pages/servlet/oauth2/oauth2-client.adoc">Edit this Page</a></div>
</div>
<div class="content">
<aside class="toc sidebar" data-title="Contents" data-levels="2">
<div class="toc-menu"></div>
</aside>
<article class="doc">
<div class="admonitionblock important">
<table>
<tbody><tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
<div class="paragraph">
<p> For the latest stable version, please use <a href="../../../index.html">Spring Security 5.6.3</a>!</p>
</div>
</td>
</tr></tbody>
</table>
</div>
<h1 id="page-title" class="page">OAuth 2.0 Client</h1>
<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>The OAuth 2.0 Client features provide support for the Client role as defined in the <a href="https://tools.ietf.org/html/rfc6749#section-1.1">OAuth 2.0 Authorization Framework</a>.</p>
</div>
<div class="paragraph">
<p>At a high-level, the core features available are:</p>
</div>
<div class="ulist">
<div class="title">Authorization Grant support</div>
<ul>
<li>
<p><a href="https://tools.ietf.org/html/rfc6749#section-1.3.1">Authorization Code</a></p>
</li>
<li>
<p><a href="https://tools.ietf.org/html/rfc6749#section-6">Refresh Token</a></p>
</li>
<li>
<p><a href="https://tools.ietf.org/html/rfc6749#section-1.3.4">Client Credentials</a></p>
</li>
<li>
<p><a href="https://tools.ietf.org/html/rfc6749#section-1.3.3">Resource Owner Password Credentials</a></p>
</li>
<li>
<p><a href="https://datatracker.ietf.org/doc/html/rfc7523#section-2.1">JWT Bearer</a></p>
</li>
</ul>
</div>
<div class="ulist">
<div class="title">Client Authentication support</div>
<ul>
<li>
<p><a href="https://datatracker.ietf.org/doc/html/rfc7523#section-2.2">JWT Bearer</a></p>
</li>
</ul>
</div>
<div class="ulist">
<div class="title">HTTP Client support</div>
<ul>
<li>
<p><a href="oauth2-client.html#oauth2Client-webclient-servlet"><code>WebClient</code> integration for Servlet Environments</a> (for requesting protected resources)</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>The <code>HttpSecurity.oauth2Client()</code> DSL provides a number of configuration options for customizing the core components used by OAuth 2.0 Client.
In addition, <code>HttpSecurity.oauth2Client().authorizationCodeGrant()</code> enables the customization of the Authorization Code grant.</p>
</div>
<div class="paragraph">
<p>The following code shows the complete configuration options provided by the <code>HttpSecurity.oauth2Client()</code> DSL:</p>
</div>
<div class="exampleblock">
<div class="title">Example 1. OAuth2 Client Configuration Options</div>
<div class="content">
<div class="listingblock primary">
<div class="title">Java</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@EnableWebSecurity
public class OAuth2ClientSecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			.oauth2Client(oauth2 -&gt; oauth2
				.clientRegistrationRepository(this.clientRegistrationRepository())
				.authorizedClientRepository(this.authorizedClientRepository())
				.authorizedClientService(this.authorizedClientService())
				.authorizationCodeGrant(codeGrant -&gt; codeGrant
					.authorizationRequestRepository(this.authorizationRequestRepository())
					.authorizationRequestResolver(this.authorizationRequestResolver())
					.accessTokenResponseClient(this.accessTokenResponseClient())
				)
			);
	}
}</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Kotlin</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-kotlin hljs" data-lang="kotlin">@EnableWebSecurity
class OAuth2ClientSecurityConfig : WebSecurityConfigurerAdapter() {

    override fun configure(http: HttpSecurity) {
        http {
            oauth2Client {
                clientRegistrationRepository = clientRegistrationRepository()
                authorizedClientRepository = authorizedClientRepository()
                authorizedClientService = authorizedClientService()
                authorizationCodeGrant {
                    authorizationRequestRepository = authorizationRequestRepository()
                    authorizationRequestResolver = authorizationRequestResolver()
                    accessTokenResponseClient = accessTokenResponseClient()
                }
            }
        }
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>In addition to the <code>HttpSecurity.oauth2Client()</code> DSL, XML configuration is also supported.</p>
</div>
<div class="paragraph">
<p>The following code shows the complete configuration options available in the <a href="../appendix/namespace.html#nsa-oauth2-client" class="xref page"> security namespace</a>:</p>
</div>
<div class="exampleblock">
<div class="title">Example 2. OAuth2 Client XML Configuration Options</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;http&gt;
	&lt;oauth2-client client-registration-repository-ref="clientRegistrationRepository"
				   authorized-client-repository-ref="authorizedClientRepository"
				   authorized-client-service-ref="authorizedClientService"&gt;
		&lt;authorization-code-grant
				authorization-request-repository-ref="authorizationRequestRepository"
				authorization-request-resolver-ref="authorizationRequestResolver"
				access-token-response-client-ref="accessTokenResponseClient"/&gt;
	&lt;/oauth2-client&gt;
&lt;/http&gt;</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>The <code>OAuth2AuthorizedClientManager</code> is responsible for managing the authorization (or re-authorization) of an OAuth 2.0 Client, in collaboration with one or more <code>OAuth2AuthorizedClientProvider</code>(s).</p>
</div>
<div class="paragraph">
<p>The following code shows an example of how to register an <code>OAuth2AuthorizedClientManager</code> <code>@Bean</code> and associate it with an <code>OAuth2AuthorizedClientProvider</code> composite that provides support for the <code>authorization_code</code>, <code>refresh_token</code>, <code>client_credentials</code> and <code>password</code> authorization grant types:</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock primary">
<div class="title">Java</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Bean
public OAuth2AuthorizedClientManager authorizedClientManager(
		ClientRegistrationRepository clientRegistrationRepository,
		OAuth2AuthorizedClientRepository authorizedClientRepository) {

	OAuth2AuthorizedClientProvider authorizedClientProvider =
			OAuth2AuthorizedClientProviderBuilder.builder()
					.authorizationCode()
					.refreshToken()
					.clientCredentials()
					.password()
					.build();

	DefaultOAuth2AuthorizedClientManager authorizedClientManager =
			new DefaultOAuth2AuthorizedClientManager(
					clientRegistrationRepository, authorizedClientRepository);
	authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

	return authorizedClientManager;
}</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Kotlin</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-kotlin hljs" data-lang="kotlin">@Bean
fun authorizedClientManager(
        clientRegistrationRepository: ClientRegistrationRepository,
        authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager {
    val authorizedClientProvider: OAuth2AuthorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
            .authorizationCode()
            .refreshToken()
            .clientCredentials()
            .password()
            .build()
    val authorizedClientManager = DefaultOAuth2AuthorizedClientManager(
            clientRegistrationRepository, authorizedClientRepository)
    authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
    return authorizedClientManager
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>The following sections will go into more detail on the core components used by OAuth 2.0 Client and the configuration options available:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="oauth2-client.html#oauth2Client-core-interface-class">Core Interfaces / Classes</a></p>
<div class="ulist">
<ul>
<li>
<p><a href="oauth2-client.html#oauth2Client-client-registration">ClientRegistration</a></p>
</li>
<li>
<p><a href="oauth2-client.html#oauth2Client-client-registration-repo">ClientRegistrationRepository</a></p>
</li>
<li>
<p><a href="oauth2-client.html#oauth2Client-authorized-client">OAuth2AuthorizedClient</a></p>
</li>
<li>
<p><a href="oauth2-client.html#oauth2Client-authorized-repo-service">OAuth2AuthorizedClientRepository / OAuth2AuthorizedClientService</a></p>
</li>
<li>
<p><a href="oauth2-client.html#oauth2Client-authorized-manager-provider">OAuth2AuthorizedClientManager / OAuth2AuthorizedClientProvider</a></p>
</li>
</ul>
</div>
</li>
<li>
<p><a href="oauth2-client.html#oauth2Client-auth-grant-support">Authorization Grant Support</a></p>
<div class="ulist">
<ul>
<li>
<p><a href="oauth2-client.html#oauth2Client-auth-code-grant">Authorization Code</a></p>
</li>
<li>
<p><a href="oauth2-client.html#oauth2Client-refresh-token-grant">Refresh Token</a></p>
</li>
<li>
<p><a href="oauth2-client.html#oauth2Client-client-creds-grant">Client Credentials</a></p>
</li>
<li>
<p><a href="oauth2-client.html#oauth2Client-password-grant">Resource Owner Password Credentials</a></p>
</li>
<li>
<p><a href="oauth2-client.html#oauth2Client-jwt-bearer-grant">JWT Bearer</a></p>
</li>
</ul>
</div>
</li>
<li>
<p><a href="oauth2-client.html#oauth2Client-client-auth-support">Client Authentication Support</a></p>
<div class="ulist">
<ul>
<li>
<p><a href="oauth2-client.html#oauth2Client-jwt-bearer-auth">JWT Bearer</a></p>
</li>
</ul>
</div>
</li>
<li>
<p><a href="oauth2-client.html#oauth2Client-additional-features">Additional Features</a></p>
<div class="ulist">
<ul>
<li>
<p><a href="oauth2-client.html#oauth2Client-registered-authorized-client">Resolving an Authorized Client</a></p>
</li>
</ul>
</div>
</li>
<li>
<p><a href="oauth2-client.html#oauth2Client-webclient-servlet">WebClient integration for Servlet Environments</a></p>
</li>
</ul>
</div>
</div>
</div>
<div class="sect1">
<h2 id="oauth2Client-core-interface-class"><a class="anchor" href="oauth2-client.html#oauth2Client-core-interface-class"></a>Core Interfaces / Classes</h2>
<div class="sectionbody">
<div class="sect2">
<h3 id="oauth2Client-client-registration"><a class="anchor" href="oauth2-client.html#oauth2Client-client-registration"></a>ClientRegistration</h3>
<div class="paragraph">
<p><code>ClientRegistration</code> is a representation of a client registered with an OAuth 2.0 or OpenID Connect 1.0 Provider.</p>
</div>
<div class="paragraph">
<p>A client registration holds information, such as client id, client secret, authorization grant type, redirect URI, scope(s), authorization URI, token URI, and other details.</p>
</div>
<div class="paragraph">
<p><code>ClientRegistration</code> and its properties are defined as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">public final class ClientRegistration {
	private String registrationId;	<i class="conum" data-value="1"></i><b>(1)</b>
	private String clientId;	<i class="conum" data-value="2"></i><b>(2)</b>
	private String clientSecret;	<i class="conum" data-value="3"></i><b>(3)</b>
	private ClientAuthenticationMethod clientAuthenticationMethod;	<i class="conum" data-value="4"></i><b>(4)</b>
	private AuthorizationGrantType authorizationGrantType;	<i class="conum" data-value="5"></i><b>(5)</b>
	private String redirectUri;	<i class="conum" data-value="6"></i><b>(6)</b>
	private Set&lt;String&gt; scopes;	<i class="conum" data-value="7"></i><b>(7)</b>
	private ProviderDetails providerDetails;
	private String clientName;	<i class="conum" data-value="8"></i><b>(8)</b>

	public class ProviderDetails {
		private String authorizationUri;	<i class="conum" data-value="9"></i><b>(9)</b>
		private String tokenUri;	<i class="conum" data-value="10"></i><b>(10)</b>
		private UserInfoEndpoint userInfoEndpoint;
		private String jwkSetUri;	<i class="conum" data-value="11"></i><b>(11)</b>
		private String issuerUri;	<i class="conum" data-value="12"></i><b>(12)</b>
        private Map&lt;String, Object&gt; configurationMetadata;  <i class="conum" data-value="13"></i><b>(13)</b>

		public class UserInfoEndpoint {
			private String uri;	<i class="conum" data-value="14"></i><b>(14)</b>
            private AuthenticationMethod authenticationMethod;  <i class="conum" data-value="15"></i><b>(15)</b>
			private String userNameAttributeName;	<i class="conum" data-value="16"></i><b>(16)</b>

		}
	}
}</code></pre>
</div>
</div>
<div class="colist arabic">
<table>
<tr>
<td><i class="conum" data-value="1"></i><b>1</b></td>
<td><code>registrationId</code>: The ID that uniquely identifies the <code>ClientRegistration</code>.</td>
</tr>
<tr>
<td><i class="conum" data-value="2"></i><b>2</b></td>
<td><code>clientId</code>: The client identifier.</td>
</tr>
<tr>
<td><i class="conum" data-value="3"></i><b>3</b></td>
<td><code>clientSecret</code>: The client secret.</td>
</tr>
<tr>
<td><i class="conum" data-value="4"></i><b>4</b></td>
<td><code>clientAuthenticationMethod</code>: The method used to authenticate the Client with the Provider.
The supported values are <strong>client_secret_basic</strong>, <strong>client_secret_post</strong>, <strong>private_key_jwt</strong>, <strong>client_secret_jwt</strong> and <strong>none</strong> <a href="https://tools.ietf.org/html/rfc6749#section-2.1">(public clients)</a>.</td>
</tr>
<tr>
<td><i class="conum" data-value="5"></i><b>5</b></td>
<td><code>authorizationGrantType</code>: The OAuth 2.0 Authorization Framework defines four <a href="https://tools.ietf.org/html/rfc6749#section-1.3">Authorization Grant</a> types.
The supported values are <code>authorization_code</code>, <code>client_credentials</code>, <code>password</code>, as well as, extension grant type <code>urn:ietf:params:oauth:grant-type:jwt-bearer</code>.</td>
</tr>
<tr>
<td><i class="conum" data-value="6"></i><b>6</b></td>
<td><code>redirectUri</code>: The client&#8217;s registered redirect URI that the <em>Authorization Server</em> redirects the end-user&#8217;s user-agent
to after the end-user has authenticated and authorized access to the client.</td>
</tr>
<tr>
<td><i class="conum" data-value="7"></i><b>7</b></td>
<td><code>scopes</code>: The scope(s) requested by the client during the Authorization Request flow, such as openid, email, or profile.</td>
</tr>
<tr>
<td><i class="conum" data-value="8"></i><b>8</b></td>
<td><code>clientName</code>: A descriptive name used for the client.
The name may be used in certain scenarios, such as when displaying the name of the client in the auto-generated login page.</td>
</tr>
<tr>
<td><i class="conum" data-value="9"></i><b>9</b></td>
<td><code>authorizationUri</code>: The Authorization Endpoint URI for the Authorization Server.</td>
</tr>
<tr>
<td><i class="conum" data-value="10"></i><b>10</b></td>
<td><code>tokenUri</code>: The Token Endpoint URI for the Authorization Server.</td>
</tr>
<tr>
<td><i class="conum" data-value="11"></i><b>11</b></td>
<td><code>jwkSetUri</code>: The URI used to retrieve the <a href="https://tools.ietf.org/html/rfc7517">JSON Web Key (JWK)</a> Set from the Authorization Server,
which contains the cryptographic key(s) used to verify the <a href="https://tools.ietf.org/html/rfc7515">JSON Web Signature (JWS)</a> of the ID Token and optionally the UserInfo Response.</td>
</tr>
<tr>
<td><i class="conum" data-value="12"></i><b>12</b></td>
<td><code>issuerUri</code>: Returns the issuer identifier uri for the OpenID Connect 1.0 provider or the OAuth 2.0 Authorization Server.</td>
</tr>
<tr>
<td><i class="conum" data-value="13"></i><b>13</b></td>
<td><code>configurationMetadata</code>: The <a href="https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig">OpenID Provider Configuration Information</a>.
This information will only be available if the Spring Boot 2.x property <code>spring.security.oauth2.client.provider.[providerId].issuerUri</code> is configured.</td>
</tr>
<tr>
<td><i class="conum" data-value="14"></i><b>14</b></td>
<td><code>(userInfoEndpoint)uri</code>: The UserInfo Endpoint URI used to access the claims/attributes of the authenticated end-user.</td>
</tr>
<tr>
<td><i class="conum" data-value="15"></i><b>15</b></td>
<td><code>(userInfoEndpoint)authenticationMethod</code>: The authentication method used when sending the access token to the UserInfo Endpoint.
The supported values are <strong>header</strong>, <strong>form</strong> and <strong>query</strong>.</td>
</tr>
<tr>
<td><i class="conum" data-value="16"></i><b>16</b></td>
<td><code>userNameAttributeName</code>: The name of the attribute returned in the UserInfo Response that references the Name or Identifier of the end-user.</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>A <code>ClientRegistration</code> can be initially configured using discovery of an OpenID Connect Provider&#8217;s <a href="https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig">Configuration endpoint</a> or an Authorization Server&#8217;s <a href="https://tools.ietf.org/html/rfc8414#section-3">Metadata endpoint</a>.</p>
</div>
<div class="paragraph">
<p><code>ClientRegistrations</code> provides convenience methods for configuring a <code>ClientRegistration</code> in this way, as can be seen in the following example:</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock primary">
<div class="title">Java</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">ClientRegistration clientRegistration =
    ClientRegistrations.fromIssuerLocation("https://idp.example.com/issuer").build();</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Kotlin</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-kotlin hljs" data-lang="kotlin">val clientRegistration = ClientRegistrations.fromIssuerLocation("https://idp.example.com/issuer").build()</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>The above code will query in series <code><a href="https://idp.example.com/issuer/.well-known/openid-configuration" class="bare">https://idp.example.com/issuer/.well-known/openid-configuration</a></code>, and then <code><a href="https://idp.example.com/.well-known/openid-configuration/issuer" class="bare">https://idp.example.com/.well-known/openid-configuration/issuer</a></code>, and finally <code><a href="https://idp.example.com/.well-known/oauth-authorization-server/issuer" class="bare">https://idp.example.com/.well-known/oauth-authorization-server/issuer</a></code>, stopping at the first to return a 200 response.</p>
</div>
<div class="paragraph">
<p>As an alternative, you can use <code>ClientRegistrations.fromOidcIssuerLocation()</code> to only query the OpenID Connect Provider&#8217;s Configuration endpoint.</p>
</div>
</div>
<div class="sect2">
<h3 id="oauth2Client-client-registration-repo"><a class="anchor" href="oauth2-client.html#oauth2Client-client-registration-repo"></a>ClientRegistrationRepository</h3>
<div class="paragraph">
<p>The <code>ClientRegistrationRepository</code> serves as a repository for OAuth 2.0 / OpenID Connect 1.0 <code>ClientRegistration</code>(s).</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Client registration information is ultimately stored and owned by the associated Authorization Server.
This repository provides the ability to retrieve a sub-set of the primary client registration information, which is stored with the Authorization Server.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Spring Boot 2.x auto-configuration binds each of the properties under <code>spring.security.oauth2.client.registration.<em>[registrationId]</em></code> to an instance of <code>ClientRegistration</code> and then composes each of the <code>ClientRegistration</code> instance(s) within a <code>ClientRegistrationRepository</code>.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
The default implementation of <code>ClientRegistrationRepository</code> is <code>InMemoryClientRegistrationRepository</code>.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The auto-configuration also registers the <code>ClientRegistrationRepository</code> as a <code>@Bean</code> in the <code>ApplicationContext</code> so that it is available for dependency-injection, if needed by the application.</p>
</div>
<div class="paragraph">
<p>The following listing shows an example:</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock primary">
<div class="title">Java</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Controller
public class OAuth2ClientController {

	@Autowired
	private ClientRegistrationRepository clientRegistrationRepository;

	@GetMapping("/")
	public String index() {
		ClientRegistration oktaRegistration =
			this.clientRegistrationRepository.findByRegistrationId("okta");

		...

		return "index";
	}
}</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Kotlin</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-kotlin hljs" data-lang="kotlin">@Controller
class OAuth2ClientController {

    @Autowired
    private lateinit var clientRegistrationRepository: ClientRegistrationRepository

    @GetMapping("/")
    fun index(): String {
        val oktaRegistration =
                this.clientRegistrationRepository.findByRegistrationId("okta")

        //...

        return "index";
    }
}</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="oauth2Client-authorized-client"><a class="anchor" href="oauth2-client.html#oauth2Client-authorized-client"></a>OAuth2AuthorizedClient</h3>
<div class="paragraph">
<p><code>OAuth2AuthorizedClient</code> is a representation of an Authorized Client.
A client is considered to be authorized when the end-user (Resource Owner) has granted authorization to the client to access its protected resources.</p>
</div>
<div class="paragraph">
<p><code>OAuth2AuthorizedClient</code> serves the purpose of associating an <code>OAuth2AccessToken</code> (and optional <code>OAuth2RefreshToken</code>) to a <code>ClientRegistration</code> (client) and resource owner, who is the <code>Principal</code> end-user that granted the authorization.</p>
</div>
</div>
<div class="sect2">
<h3 id="oauth2Client-authorized-repo-service"><a class="anchor" href="oauth2-client.html#oauth2Client-authorized-repo-service"></a>OAuth2AuthorizedClientRepository / OAuth2AuthorizedClientService</h3>
<div class="paragraph">
<p><code>OAuth2AuthorizedClientRepository</code> is responsible for persisting <code>OAuth2AuthorizedClient</code>(s) between web requests.
Whereas, the primary role of <code>OAuth2AuthorizedClientService</code> is to manage <code>OAuth2AuthorizedClient</code>(s) at the application-level.</p>
</div>
<div class="paragraph">
<p>From a developer perspective, the <code>OAuth2AuthorizedClientRepository</code> or <code>OAuth2AuthorizedClientService</code> provides the capability to lookup an <code>OAuth2AccessToken</code> associated with a client so that it may be used to initiate a protected resource request.</p>
</div>
<div class="paragraph">
<p>The following listing shows an example:</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock primary">
<div class="title">Java</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Controller
public class OAuth2ClientController {

    @Autowired
    private OAuth2AuthorizedClientService authorizedClientService;

    @GetMapping("/")
    public String index(Authentication authentication) {
        OAuth2AuthorizedClient authorizedClient =
            this.authorizedClientService.loadAuthorizedClient("okta", authentication.getName());

        OAuth2AccessToken accessToken = authorizedClient.getAccessToken();

        ...

        return "index";
    }
}</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Kotlin</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-kotlin hljs" data-lang="kotlin">@Controller
class OAuth2ClientController {

    @Autowired
    private lateinit var authorizedClientService: OAuth2AuthorizedClientService

    @GetMapping("/")
    fun index(authentication: Authentication): String {
        val authorizedClient: OAuth2AuthorizedClient =
            this.authorizedClientService.loadAuthorizedClient("okta", authentication.getName());
        val accessToken = authorizedClient.accessToken

        ...

        return "index";
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Spring Boot 2.x auto-configuration registers an <code>OAuth2AuthorizedClientRepository</code> and/or <code>OAuth2AuthorizedClientService</code> <code>@Bean</code> in the <code>ApplicationContext</code>.
However, the application may choose to override and register a custom <code>OAuth2AuthorizedClientRepository</code> or <code>OAuth2AuthorizedClientService</code> <code>@Bean</code>.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The default implementation of <code>OAuth2AuthorizedClientService</code> is <code>InMemoryOAuth2AuthorizedClientService</code>, which stores <code>OAuth2AuthorizedClient</code>(s) in-memory.</p>
</div>
<div class="paragraph">
<p>Alternatively, the JDBC implementation <code>JdbcOAuth2AuthorizedClientService</code> may be configured for persisting <code>OAuth2AuthorizedClient</code>(s) in a database.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<code>JdbcOAuth2AuthorizedClientService</code> depends on the table definition described in <a href="../appendix/database-schema.html#dbschema-oauth2-client" class="xref page"> OAuth 2.0 Client Schema</a>.
</td>
</tr>
</table>
</div>
</div>
<div class="sect2">
<h3 id="oauth2Client-authorized-manager-provider"><a class="anchor" href="oauth2-client.html#oauth2Client-authorized-manager-provider"></a>OAuth2AuthorizedClientManager / OAuth2AuthorizedClientProvider</h3>
<div class="paragraph">
<p>The <code>OAuth2AuthorizedClientManager</code> is responsible for the overall management of <code>OAuth2AuthorizedClient</code>(s).</p>
</div>
<div class="paragraph">
<p>The primary responsibilities include:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Authorizing (or re-authorizing) an OAuth 2.0 Client, using an <code>OAuth2AuthorizedClientProvider</code>.</p>
</li>
<li>
<p>Delegating the persistence of an <code>OAuth2AuthorizedClient</code>, typically using an <code>OAuth2AuthorizedClientService</code> or <code>OAuth2AuthorizedClientRepository</code>.</p>
</li>
<li>
<p>Delegating to an <code>OAuth2AuthorizationSuccessHandler</code> when an OAuth 2.0 Client has been successfully authorized (or re-authorized).</p>
</li>
<li>
<p>Delegating to an <code>OAuth2AuthorizationFailureHandler</code> when an OAuth 2.0 Client fails to authorize (or re-authorize).</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>An <code>OAuth2AuthorizedClientProvider</code> implements a strategy for authorizing (or re-authorizing) an OAuth 2.0 Client.
Implementations will typically implement an authorization grant type, eg. <code>authorization_code</code>, <code>client_credentials</code>, etc.</p>
</div>
<div class="paragraph">
<p>The default implementation of <code>OAuth2AuthorizedClientManager</code> is <code>DefaultOAuth2AuthorizedClientManager</code>, which is associated with an <code>OAuth2AuthorizedClientProvider</code> that may support multiple authorization grant types using a delegation-based composite.
The <code>OAuth2AuthorizedClientProviderBuilder</code> may be used to configure and build the delegation-based composite.</p>
</div>
<div class="paragraph">
<p>The following code shows an example of how to configure and build an <code>OAuth2AuthorizedClientProvider</code> composite that provides support for the <code>authorization_code</code>, <code>refresh_token</code>, <code>client_credentials</code> and <code>password</code> authorization grant types:</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock primary">
<div class="title">Java</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Bean
public OAuth2AuthorizedClientManager authorizedClientManager(
		ClientRegistrationRepository clientRegistrationRepository,
		OAuth2AuthorizedClientRepository authorizedClientRepository) {

	OAuth2AuthorizedClientProvider authorizedClientProvider =
			OAuth2AuthorizedClientProviderBuilder.builder()
					.authorizationCode()
					.refreshToken()
					.clientCredentials()
					.password()
					.build();

	DefaultOAuth2AuthorizedClientManager authorizedClientManager =
			new DefaultOAuth2AuthorizedClientManager(
					clientRegistrationRepository, authorizedClientRepository);
	authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

	return authorizedClientManager;
}</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Kotlin</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-kotlin hljs" data-lang="kotlin">@Bean
fun authorizedClientManager(
        clientRegistrationRepository: ClientRegistrationRepository,
        authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager {
    val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
            .authorizationCode()
            .refreshToken()
            .clientCredentials()
            .password()
            .build()
    val authorizedClientManager = DefaultOAuth2AuthorizedClientManager(
            clientRegistrationRepository, authorizedClientRepository)
    authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
    return authorizedClientManager
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>When an authorization attempt succeeds, the <code>DefaultOAuth2AuthorizedClientManager</code> will delegate to the <code>OAuth2AuthorizationSuccessHandler</code>, which (by default) will save the <code>OAuth2AuthorizedClient</code> via the <code>OAuth2AuthorizedClientRepository</code>.
In the case of a re-authorization failure, eg. a refresh token is no longer valid, the previously saved <code>OAuth2AuthorizedClient</code> will be removed from the <code>OAuth2AuthorizedClientRepository</code> via the <code>RemoveAuthorizedClientOAuth2AuthorizationFailureHandler</code>.
The default behaviour may be customized via <code>setAuthorizationSuccessHandler(OAuth2AuthorizationSuccessHandler)</code> and <code>setAuthorizationFailureHandler(OAuth2AuthorizationFailureHandler)</code>.</p>
</div>
<div class="paragraph">
<p>The <code>DefaultOAuth2AuthorizedClientManager</code> is also associated with a <code>contextAttributesMapper</code> of type <code>Function&lt;OAuth2AuthorizeRequest, Map&lt;String, Object&gt;&gt;</code>, which is responsible for mapping attribute(s) from the <code>OAuth2AuthorizeRequest</code> to a <code>Map</code> of attributes to be associated to the <code>OAuth2AuthorizationContext</code>.
This can be useful when you need to supply an <code>OAuth2AuthorizedClientProvider</code> with required (supported) attribute(s), eg. the <code>PasswordOAuth2AuthorizedClientProvider</code> requires the resource owner&#8217;s <code>username</code> and <code>password</code> to be available in <code>OAuth2AuthorizationContext.getAttributes()</code>.</p>
</div>
<div class="paragraph">
<p>The following code shows an example of the <code>contextAttributesMapper</code>:</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock primary">
<div class="title">Java</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Bean
public OAuth2AuthorizedClientManager authorizedClientManager(
		ClientRegistrationRepository clientRegistrationRepository,
		OAuth2AuthorizedClientRepository authorizedClientRepository) {

	OAuth2AuthorizedClientProvider authorizedClientProvider =
			OAuth2AuthorizedClientProviderBuilder.builder()
					.password()
					.refreshToken()
					.build();

	DefaultOAuth2AuthorizedClientManager authorizedClientManager =
			new DefaultOAuth2AuthorizedClientManager(
					clientRegistrationRepository, authorizedClientRepository);
	authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

	// Assuming the `username` and `password` are supplied as `HttpServletRequest` parameters,
	// map the `HttpServletRequest` parameters to `OAuth2AuthorizationContext.getAttributes()`
	authorizedClientManager.setContextAttributesMapper(contextAttributesMapper());

	return authorizedClientManager;
}

private Function&lt;OAuth2AuthorizeRequest, Map&lt;String, Object&gt;&gt; contextAttributesMapper() {
	return authorizeRequest -&gt; {
		Map&lt;String, Object&gt; contextAttributes = Collections.emptyMap();
		HttpServletRequest servletRequest = authorizeRequest.getAttribute(HttpServletRequest.class.getName());
		String username = servletRequest.getParameter(OAuth2ParameterNames.USERNAME);
		String password = servletRequest.getParameter(OAuth2ParameterNames.PASSWORD);
		if (StringUtils.hasText(username) &amp;&amp; StringUtils.hasText(password)) {
			contextAttributes = new HashMap&lt;&gt;();

			// `PasswordOAuth2AuthorizedClientProvider` requires both attributes
			contextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username);
			contextAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password);
		}
		return contextAttributes;
	};
}</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Kotlin</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-kotlin hljs" data-lang="kotlin">@Bean
fun authorizedClientManager(
        clientRegistrationRepository: ClientRegistrationRepository,
        authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager {
    val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
            .password()
            .refreshToken()
            .build()
    val authorizedClientManager = DefaultOAuth2AuthorizedClientManager(
            clientRegistrationRepository, authorizedClientRepository)
    authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)

    // Assuming the `username` and `password` are supplied as `HttpServletRequest` parameters,
    // map the `HttpServletRequest` parameters to `OAuth2AuthorizationContext.getAttributes()`
    authorizedClientManager.setContextAttributesMapper(contextAttributesMapper())
    return authorizedClientManager
}

private fun contextAttributesMapper(): Function&lt;OAuth2AuthorizeRequest, MutableMap&lt;String, Any&gt;&gt; {
    return Function { authorizeRequest -&gt;
        var contextAttributes: MutableMap&lt;String, Any&gt; = mutableMapOf()
        val servletRequest: HttpServletRequest = authorizeRequest.getAttribute(HttpServletRequest::class.java.name)
        val username: String = servletRequest.getParameter(OAuth2ParameterNames.USERNAME)
        val password: String = servletRequest.getParameter(OAuth2ParameterNames.PASSWORD)
        if (StringUtils.hasText(username) &amp;&amp; StringUtils.hasText(password)) {
            contextAttributes = hashMapOf()

            // `PasswordOAuth2AuthorizedClientProvider` requires both attributes
            contextAttributes[OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME] = username
            contextAttributes[OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME] = password
        }
        contextAttributes
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>The <code>DefaultOAuth2AuthorizedClientManager</code> is designed to be used <strong><em>within</em></strong> the context of a <code>HttpServletRequest</code>.
When operating <strong><em>outside</em></strong> of a <code>HttpServletRequest</code> context, use <code>AuthorizedClientServiceOAuth2AuthorizedClientManager</code> instead.</p>
</div>
<div class="paragraph">
<p>A <em>service application</em> is a common use case for when to use an <code>AuthorizedClientServiceOAuth2AuthorizedClientManager</code>.
Service applications often run in the background, without any user interaction, and typically run under a system-level account instead of a user account.
An OAuth 2.0 Client configured with the <code>client_credentials</code> grant type can be considered a type of service application.</p>
</div>
<div class="paragraph">
<p>The following code shows an example of how to configure an <code>AuthorizedClientServiceOAuth2AuthorizedClientManager</code> that provides support for the <code>client_credentials</code> grant type:</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock primary">
<div class="title">Java</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Bean
public OAuth2AuthorizedClientManager authorizedClientManager(
		ClientRegistrationRepository clientRegistrationRepository,
		OAuth2AuthorizedClientService authorizedClientService) {

	OAuth2AuthorizedClientProvider authorizedClientProvider =
			OAuth2AuthorizedClientProviderBuilder.builder()
					.clientCredentials()
					.build();

	AuthorizedClientServiceOAuth2AuthorizedClientManager authorizedClientManager =
			new AuthorizedClientServiceOAuth2AuthorizedClientManager(
					clientRegistrationRepository, authorizedClientService);
	authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

	return authorizedClientManager;
}</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Kotlin</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-kotlin hljs" data-lang="kotlin">@Bean
fun authorizedClientManager(
        clientRegistrationRepository: ClientRegistrationRepository,
        authorizedClientService: OAuth2AuthorizedClientService): OAuth2AuthorizedClientManager {
    val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
            .clientCredentials()
            .build()
    val authorizedClientManager = AuthorizedClientServiceOAuth2AuthorizedClientManager(
            clientRegistrationRepository, authorizedClientService)
    authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
    return authorizedClientManager
}</code></pre>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="oauth2Client-auth-grant-support"><a class="anchor" href="oauth2-client.html#oauth2Client-auth-grant-support"></a>Authorization Grant Support</h2>
<div class="sectionbody">
<div class="sect2">
<h3 id="oauth2Client-auth-code-grant"><a class="anchor" href="oauth2-client.html#oauth2Client-auth-code-grant"></a>Authorization Code</h3>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Please refer to the OAuth 2.0 Authorization Framework for further details on the <a href="https://tools.ietf.org/html/rfc6749#section-1.3.1">Authorization Code</a> grant.
</td>
</tr>
</table>
</div>
<div class="sect3">
<h4 id="_obtaining_authorization"><a class="anchor" href="oauth2-client.html#_obtaining_authorization"></a>Obtaining Authorization</h4>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Please refer to the <a href="https://tools.ietf.org/html/rfc6749#section-4.1.1">Authorization Request/Response</a> protocol flow for the Authorization Code grant.
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_initiating_the_authorization_request"><a class="anchor" href="oauth2-client.html#_initiating_the_authorization_request"></a>Initiating the Authorization Request</h4>
<div class="paragraph">
<p>The <code>OAuth2AuthorizationRequestRedirectFilter</code> uses an <code>OAuth2AuthorizationRequestResolver</code> to resolve an <code>OAuth2AuthorizationRequest</code> and initiate the Authorization Code grant flow by redirecting the end-user&#8217;s user-agent to the Authorization Server&#8217;s Authorization Endpoint.</p>
</div>
<div class="paragraph">
<p>The primary role of the <code>OAuth2AuthorizationRequestResolver</code> is to resolve an <code>OAuth2AuthorizationRequest</code> from the provided web request.
The default implementation <code>DefaultOAuth2AuthorizationRequestResolver</code> matches on the (default) path <code>/oauth2/authorization/{registrationId}</code> extracting the <code>registrationId</code> and using it to build the <code>OAuth2AuthorizationRequest</code> for the associated <code>ClientRegistration</code>.</p>
</div>
<div class="paragraph">
<p>Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">spring:
  security:
    oauth2:
      client:
        registration:
          okta:
            client-id: okta-client-id
            client-secret: okta-client-secret
            authorization-grant-type: authorization_code
            redirect-uri: "{baseUrl}/authorized/okta"
            scope: read, write
        provider:
          okta:
            authorization-uri: https://dev-1234.oktapreview.com/oauth2/v1/authorize
            token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token</code></pre>
</div>
</div>
<div class="paragraph">
<p>A request with the base path <code>/oauth2/authorization/okta</code> will initiate the Authorization Request redirect by the <code>OAuth2AuthorizationRequestRedirectFilter</code> and ultimately start the Authorization Code grant flow.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
The <code>AuthorizationCodeOAuth2AuthorizedClientProvider</code> is an implementation of <code>OAuth2AuthorizedClientProvider</code> for the Authorization Code grant,
which also initiates the Authorization Request redirect by the <code>OAuth2AuthorizationRequestRedirectFilter</code>.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>If the OAuth 2.0 Client is a <a href="https://tools.ietf.org/html/rfc6749#section-2.1">Public Client</a>, then configure the OAuth 2.0 Client registration as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">spring:
  security:
    oauth2:
      client:
        registration:
          okta:
            client-id: okta-client-id
            client-authentication-method: none
            authorization-grant-type: authorization_code
            redirect-uri: "{baseUrl}/authorized/okta"
            ...</code></pre>
</div>
</div>
<div class="paragraph">
<p>Public Clients are supported using <a href="https://tools.ietf.org/html/rfc7636">Proof Key for Code Exchange</a> (PKCE).
If the client is running in an untrusted environment (eg. native application or web browser-based application) and therefore incapable of maintaining the confidentiality of it&#8217;s credentials, PKCE will automatically be used when the following conditions are true:</p>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p><code>client-secret</code> is omitted (or empty)</p>
</li>
<li>
<p><code>client-authentication-method</code> is set to "none" (<code>ClientAuthenticationMethod.NONE</code>)</p>
</li>
</ol>
</div>
<div id="oauth2Client-auth-code-redirect-uri" class="paragraph">
<p>The <code>DefaultOAuth2AuthorizationRequestResolver</code> also supports <code>URI</code> template variables for the <code>redirect-uri</code> using <code>UriComponentsBuilder</code>.</p>
</div>
<div class="paragraph">
<p>The following configuration uses all the supported <code>URI</code> template variables:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">spring:
  security:
    oauth2:
      client:
        registration:
          okta:
            ...
            redirect-uri: "{baseScheme}://{baseHost}{basePort}{basePath}/authorized/{registrationId}"
            ...</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<code>{baseUrl}</code> resolves to <code>{baseScheme}://{baseHost}{basePort}{basePath}</code>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Configuring the <code>redirect-uri</code> with <code>URI</code> template variables is especially useful when the OAuth 2.0 Client is running behind a <a href="../../features/exploits/http.html#http-proxy-server" class="xref page">Proxy Server</a>.
This ensures that the <code>X-Forwarded-*</code> headers are used when expanding the <code>redirect-uri</code>.</p>
</div>
</div>
<div class="sect3">
<h4 id="_customizing_the_authorization_request"><a class="anchor" href="oauth2-client.html#_customizing_the_authorization_request"></a>Customizing the Authorization Request</h4>
<div class="paragraph">
<p>One of the primary use cases an <code>OAuth2AuthorizationRequestResolver</code> can realize is the ability to customize the Authorization Request with additional parameters above the standard parameters defined in the OAuth 2.0 Authorization Framework.</p>
</div>
<div class="paragraph">
<p>For example, OpenID Connect defines additional OAuth 2.0 request parameters for the <a href="https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest">Authorization Code Flow</a> extending from the standard parameters defined in the <a href="https://tools.ietf.org/html/rfc6749#section-4.1.1">OAuth 2.0 Authorization Framework</a>.
One of those extended parameters is the <code>prompt</code> parameter.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
OPTIONAL. Space delimited, case sensitive list of ASCII string values that specifies whether the Authorization Server prompts the End-User for reauthentication and consent. The defined values are: none, login, consent, select_account
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The following example shows how to configure the <code>DefaultOAuth2AuthorizationRequestResolver</code> with a <code>Consumer&lt;OAuth2AuthorizationRequest.Builder&gt;</code> that customizes the Authorization Request for <code>oauth2Login()</code>, by including the request parameter <code>prompt=consent</code>.</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock primary">
<div class="title">Java</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@EnableWebSecurity
public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private ClientRegistrationRepository clientRegistrationRepository;

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			.authorizeRequests(authorize -&gt; authorize
				.anyRequest().authenticated()
			)
			.oauth2Login(oauth2 -&gt; oauth2
				.authorizationEndpoint(authorization -&gt; authorization
					.authorizationRequestResolver(
						authorizationRequestResolver(this.clientRegistrationRepository)
					)
				)
			);
	}

	private OAuth2AuthorizationRequestResolver authorizationRequestResolver(
			ClientRegistrationRepository clientRegistrationRepository) {

		DefaultOAuth2AuthorizationRequestResolver authorizationRequestResolver =
				new DefaultOAuth2AuthorizationRequestResolver(
						clientRegistrationRepository, "/oauth2/authorization");
		authorizationRequestResolver.setAuthorizationRequestCustomizer(
				authorizationRequestCustomizer());

		return  authorizationRequestResolver;
	}

	private Consumer&lt;OAuth2AuthorizationRequest.Builder&gt; authorizationRequestCustomizer() {
		return customizer -&gt; customizer
					.additionalParameters(params -&gt; params.put("prompt", "consent"));
	}
}</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Kotlin</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-kotlin hljs" data-lang="kotlin">@EnableWebSecurity
class SecurityConfig : WebSecurityConfigurerAdapter() {

    @Autowired
    private lateinit var customClientRegistrationRepository: ClientRegistrationRepository

    override fun configure(http: HttpSecurity) {
        http {
            authorizeRequests {
                authorize(anyRequest, authenticated)
            }
            oauth2Login {
                authorizationEndpoint {
                    authorizationRequestResolver = authorizationRequestResolver(customClientRegistrationRepository)
                }
            }
        }
    }

    private fun authorizationRequestResolver(
            clientRegistrationRepository: ClientRegistrationRepository?): OAuth2AuthorizationRequestResolver? {
        val authorizationRequestResolver = DefaultOAuth2AuthorizationRequestResolver(
                clientRegistrationRepository, "/oauth2/authorization")
        authorizationRequestResolver.setAuthorizationRequestCustomizer(
                authorizationRequestCustomizer())
        return authorizationRequestResolver
    }

    private fun authorizationRequestCustomizer(): Consumer&lt;OAuth2AuthorizationRequest.Builder&gt; {
        return Consumer { customizer -&gt;
            customizer
                    .additionalParameters { params -&gt; params["prompt"] = "consent" }
        }
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>For the simple use case, where the additional request parameter is always the same for a specific provider, it may be added directly in the <code>authorization-uri</code> property.</p>
</div>
<div class="paragraph">
<p>For example, if the value for the request parameter <code>prompt</code> is always <code>consent</code> for the provider <code>okta</code>, than simply configure as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">spring:
  security:
    oauth2:
      client:
        provider:
          okta:
            authorization-uri: https://dev-1234.oktapreview.com/oauth2/v1/authorize?prompt=consent</code></pre>
</div>
</div>
<div class="paragraph">
<p>The preceding example shows the common use case of adding a custom parameter on top of the standard parameters.
Alternatively, if your requirements are more advanced, you can take full control in building the Authorization Request URI by simply overriding the <code>OAuth2AuthorizationRequest.authorizationRequestUri</code> property.</p>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
<code>OAuth2AuthorizationRequest.Builder.build()</code> constructs the <code>OAuth2AuthorizationRequest.authorizationRequestUri</code>, which represents the Authorization Request URI including all query parameters using the <code>application/x-www-form-urlencoded</code> format.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The following example shows a variation of <code>authorizationRequestCustomizer()</code> from the preceding example, and instead overrides the <code>OAuth2AuthorizationRequest.authorizationRequestUri</code> property.</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock primary">
<div class="title">Java</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">private Consumer&lt;OAuth2AuthorizationRequest.Builder&gt; authorizationRequestCustomizer() {
	return customizer -&gt; customizer
				.authorizationRequestUri(uriBuilder -&gt; uriBuilder
					.queryParam("prompt", "consent").build());
}</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Kotlin</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-kotlin hljs" data-lang="kotlin">private fun authorizationRequestCustomizer(): Consumer&lt;OAuth2AuthorizationRequest.Builder&gt; {
    return Consumer { customizer: OAuth2AuthorizationRequest.Builder -&gt;
        customizer
                .authorizationRequestUri { uriBuilder: UriBuilder -&gt;
                    uriBuilder
                            .queryParam("prompt", "consent").build()
                }
    }
}</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_storing_the_authorization_request"><a class="anchor" href="oauth2-client.html#_storing_the_authorization_request"></a>Storing the Authorization Request</h4>
<div class="paragraph">
<p>The <code>AuthorizationRequestRepository</code> is responsible for the persistence of the <code>OAuth2AuthorizationRequest</code> from the time the Authorization Request is initiated to the time the Authorization Response is received (the callback).</p>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
The <code>OAuth2AuthorizationRequest</code> is used to correlate and validate the Authorization Response.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The default implementation of <code>AuthorizationRequestRepository</code> is <code>HttpSessionOAuth2AuthorizationRequestRepository</code>, which stores the <code>OAuth2AuthorizationRequest</code> in the <code>HttpSession</code>.</p>
</div>
<div class="paragraph">
<p>If you have a custom implementation of <code>AuthorizationRequestRepository</code>, you may configure it as shown in the following example:</p>
</div>
<div class="exampleblock">
<div class="title">Example 3. AuthorizationRequestRepository Configuration</div>
<div class="content">
<div class="listingblock primary">
<div class="title">Java</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@EnableWebSecurity
public class OAuth2ClientSecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			.oauth2Client(oauth2 -&gt; oauth2
				.authorizationCodeGrant(codeGrant -&gt; codeGrant
					.authorizationRequestRepository(this.authorizationRequestRepository())
					...
				)
			);
	}
}</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Kotlin</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-kotlin hljs" data-lang="kotlin">@EnableWebSecurity
class OAuth2ClientSecurityConfig : WebSecurityConfigurerAdapter() {

    override fun configure(http: HttpSecurity) {
        http {
            oauth2Client {
                authorizationCodeGrant {
                    authorizationRequestRepository = authorizationRequestRepository()
                }
            }
        }
    }
}</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Xml</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;http&gt;
	&lt;oauth2-client&gt;
		&lt;authorization-code-grant authorization-request-repository-ref="authorizationRequestRepository"/&gt;
	&lt;/oauth2-client&gt;
&lt;/http&gt;</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_requesting_an_access_token"><a class="anchor" href="oauth2-client.html#_requesting_an_access_token"></a>Requesting an Access Token</h4>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Please refer to the <a href="https://tools.ietf.org/html/rfc6749#section-4.1.3">Access Token Request/Response</a> protocol flow for the Authorization Code grant.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The default implementation of <code>OAuth2AccessTokenResponseClient</code> for the Authorization Code grant is <code>DefaultAuthorizationCodeTokenResponseClient</code>, which uses a <code>RestOperations</code> for exchanging an authorization code for an access token at the Authorization Server’s Token Endpoint.</p>
</div>
<div class="paragraph">
<p>The <code>DefaultAuthorizationCodeTokenResponseClient</code> is quite flexible as it allows you to customize the pre-processing of the Token Request and/or post-handling of the Token Response.</p>
</div>
</div>
<div class="sect3">
<h4 id="_customizing_the_access_token_request"><a class="anchor" href="oauth2-client.html#_customizing_the_access_token_request"></a>Customizing the Access Token Request</h4>
<div class="paragraph">
<p>If you need to customize the pre-processing of the Token Request, you can provide <code>DefaultAuthorizationCodeTokenResponseClient.setRequestEntityConverter()</code> with a custom <code>Converter&lt;OAuth2AuthorizationCodeGrantRequest, RequestEntity&lt;?&gt;&gt;</code>.
The default implementation <code>OAuth2AuthorizationCodeGrantRequestEntityConverter</code> builds a <code>RequestEntity</code> representation of a standard <a href="https://tools.ietf.org/html/rfc6749#section-4.1.3">OAuth 2.0 Access Token Request</a>.
However, providing a custom <code>Converter</code>, would allow you to extend the standard Token Request and add custom parameter(s).</p>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
The custom <code>Converter</code> must return a valid <code>RequestEntity</code> representation of an OAuth 2.0 Access Token Request that is understood by the intended OAuth 2.0 Provider.
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_customizing_the_access_token_response"><a class="anchor" href="oauth2-client.html#_customizing_the_access_token_response"></a>Customizing the Access Token Response</h4>
<div class="paragraph">
<p>On the other end, if you need to customize the post-handling of the Token Response, you will need to provide <code>DefaultAuthorizationCodeTokenResponseClient.setRestOperations()</code> with a custom configured <code>RestOperations</code>.
The default <code>RestOperations</code> is configured as follows:</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock primary">
<div class="title">Java</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">RestTemplate restTemplate = new RestTemplate(Arrays.asList(
		new FormHttpMessageConverter(),
		new OAuth2AccessTokenResponseHttpMessageConverter()));

restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Kotlin</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-kotlin hljs" data-lang="kotlin">val restTemplate = RestTemplate(listOf(
        FormHttpMessageConverter(),
        OAuth2AccessTokenResponseHttpMessageConverter()))

restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler()</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
Spring MVC <code>FormHttpMessageConverter</code> is required as it&#8217;s used when sending the OAuth 2.0 Access Token Request.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p><code>OAuth2AccessTokenResponseHttpMessageConverter</code> is a <code>HttpMessageConverter</code> for an OAuth 2.0 Access Token Response.
You can provide <code>OAuth2AccessTokenResponseHttpMessageConverter.setAccessTokenResponseConverter()</code> with a custom <code>Converter&lt;Map&lt;String, Object&gt;, OAuth2AccessTokenResponse&gt;</code> that is used for converting the OAuth 2.0 Access Token Response parameters to an <code>OAuth2AccessTokenResponse</code>.</p>
</div>
<div class="paragraph">
<p><code>OAuth2ErrorResponseErrorHandler</code> is a <code>ResponseErrorHandler</code> that can handle an OAuth 2.0 Error, eg. 400 Bad Request.
It uses an <code>OAuth2ErrorHttpMessageConverter</code> for converting the OAuth 2.0 Error parameters to an <code>OAuth2Error</code>.</p>
</div>
<div class="paragraph">
<p>Whether you customize <code>DefaultAuthorizationCodeTokenResponseClient</code> or provide your own implementation of <code>OAuth2AccessTokenResponseClient</code>, you&#8217;ll need to configure it as shown in the following example:</p>
</div>
<div class="exampleblock">
<div class="title">Example 4. Access Token Response Configuration</div>
<div class="content">
<div class="listingblock primary">
<div class="title">Java</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@EnableWebSecurity
public class OAuth2ClientSecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			.oauth2Client(oauth2 -&gt; oauth2
				.authorizationCodeGrant(codeGrant -&gt; codeGrant
					.accessTokenResponseClient(this.accessTokenResponseClient())
					...
				)
			);
	}
}</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Kotlin</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-kotlin hljs" data-lang="kotlin">@EnableWebSecurity
class OAuth2ClientSecurityConfig : WebSecurityConfigurerAdapter() {

    override fun configure(http: HttpSecurity) {
        http {
            oauth2Client {
                authorizationCodeGrant {
                    accessTokenResponseClient = accessTokenResponseClient()
                }
            }
        }
    }
}</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Xml</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;http&gt;
	&lt;oauth2-client&gt;
		&lt;authorization-code-grant access-token-response-client-ref="accessTokenResponseClient"/&gt;
	&lt;/oauth2-client&gt;
&lt;/http&gt;</code></pre>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="oauth2Client-refresh-token-grant"><a class="anchor" href="oauth2-client.html#oauth2Client-refresh-token-grant"></a>Refresh Token</h3>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Please refer to the OAuth 2.0 Authorization Framework for further details on the <a href="https://tools.ietf.org/html/rfc6749#section-1.5">Refresh Token</a>.
</td>
</tr>
</table>
</div>
<div class="sect3">
<h4 id="_refreshing_an_access_token"><a class="anchor" href="oauth2-client.html#_refreshing_an_access_token"></a>Refreshing an Access Token</h4>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Please refer to the <a href="https://tools.ietf.org/html/rfc6749#section-6">Access Token Request/Response</a> protocol flow for the Refresh Token grant.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The default implementation of <code>OAuth2AccessTokenResponseClient</code> for the Refresh Token grant is <code>DefaultRefreshTokenTokenResponseClient</code>, which uses a <code>RestOperations</code> when refreshing an access token at the Authorization Server’s Token Endpoint.</p>
</div>
<div class="paragraph">
<p>The <code>DefaultRefreshTokenTokenResponseClient</code> is quite flexible as it allows you to customize the pre-processing of the Token Request and/or post-handling of the Token Response.</p>
</div>
</div>
<div class="sect3">
<h4 id="_customizing_the_access_token_request_2"><a class="anchor" href="oauth2-client.html#_customizing_the_access_token_request_2"></a>Customizing the Access Token Request</h4>
<div class="paragraph">
<p>If you need to customize the pre-processing of the Token Request, you can provide <code>DefaultRefreshTokenTokenResponseClient.setRequestEntityConverter()</code> with a custom <code>Converter&lt;OAuth2RefreshTokenGrantRequest, RequestEntity&lt;?&gt;&gt;</code>.
The default implementation <code>OAuth2RefreshTokenGrantRequestEntityConverter</code> builds a <code>RequestEntity</code> representation of a standard <a href="https://tools.ietf.org/html/rfc6749#section-6">OAuth 2.0 Access Token Request</a>.
However, providing a custom <code>Converter</code>, would allow you to extend the standard Token Request and add custom parameter(s).</p>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
The custom <code>Converter</code> must return a valid <code>RequestEntity</code> representation of an OAuth 2.0 Access Token Request that is understood by the intended OAuth 2.0 Provider.
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_customizing_the_access_token_response_2"><a class="anchor" href="oauth2-client.html#_customizing_the_access_token_response_2"></a>Customizing the Access Token Response</h4>
<div class="paragraph">
<p>On the other end, if you need to customize the post-handling of the Token Response, you will need to provide <code>DefaultRefreshTokenTokenResponseClient.setRestOperations()</code> with a custom configured <code>RestOperations</code>.
The default <code>RestOperations</code> is configured as follows:</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock primary">
<div class="title">Java</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">RestTemplate restTemplate = new RestTemplate(Arrays.asList(
		new FormHttpMessageConverter(),
		new OAuth2AccessTokenResponseHttpMessageConverter()));

restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Kotlin</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-kotlin hljs" data-lang="kotlin">val restTemplate = RestTemplate(listOf(
        FormHttpMessageConverter(),
        OAuth2AccessTokenResponseHttpMessageConverter()))

restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler()</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
Spring MVC <code>FormHttpMessageConverter</code> is required as it&#8217;s used when sending the OAuth 2.0 Access Token Request.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p><code>OAuth2AccessTokenResponseHttpMessageConverter</code> is a <code>HttpMessageConverter</code> for an OAuth 2.0 Access Token Response.
You can provide <code>OAuth2AccessTokenResponseHttpMessageConverter.setAccessTokenResponseConverter()</code> with a custom <code>Converter&lt;Map&lt;String, Object&gt;, OAuth2AccessTokenResponse&gt;</code> that is used for converting the OAuth 2.0 Access Token Response parameters to an <code>OAuth2AccessTokenResponse</code>.</p>
</div>
<div class="paragraph">
<p><code>OAuth2ErrorResponseErrorHandler</code> is a <code>ResponseErrorHandler</code> that can handle an OAuth 2.0 Error, eg. 400 Bad Request.
It uses an <code>OAuth2ErrorHttpMessageConverter</code> for converting the OAuth 2.0 Error parameters to an <code>OAuth2Error</code>.</p>
</div>
<div class="paragraph">
<p>Whether you customize <code>DefaultRefreshTokenTokenResponseClient</code> or provide your own implementation of <code>OAuth2AccessTokenResponseClient</code>, you&#8217;ll need to configure it as shown in the following example:</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock primary">
<div class="title">Java</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">// Customize
OAuth2AccessTokenResponseClient&lt;OAuth2RefreshTokenGrantRequest&gt; refreshTokenTokenResponseClient = ...

OAuth2AuthorizedClientProvider authorizedClientProvider =
		OAuth2AuthorizedClientProviderBuilder.builder()
				.authorizationCode()
				.refreshToken(configurer -&gt; configurer.accessTokenResponseClient(refreshTokenTokenResponseClient))
				.build();

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Kotlin</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-kotlin hljs" data-lang="kotlin">// Customize
val refreshTokenTokenResponseClient: OAuth2AccessTokenResponseClient&lt;OAuth2RefreshTokenGrantRequest&gt; = ...

val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
        .authorizationCode()
        .refreshToken { it.accessTokenResponseClient(refreshTokenTokenResponseClient) }
        .build()

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<code>OAuth2AuthorizedClientProviderBuilder.builder().refreshToken()</code> configures a <code>RefreshTokenOAuth2AuthorizedClientProvider</code>,
which is an implementation of an <code>OAuth2AuthorizedClientProvider</code> for the Refresh Token grant.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The <code>OAuth2RefreshToken</code> may optionally be returned in the Access Token Response for the <code>authorization_code</code> and <code>password</code> grant types.
If the <code>OAuth2AuthorizedClient.getRefreshToken()</code> is available and the <code>OAuth2AuthorizedClient.getAccessToken()</code> is expired, it will automatically be refreshed by the <code>RefreshTokenOAuth2AuthorizedClientProvider</code>.</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="oauth2Client-client-creds-grant"><a class="anchor" href="oauth2-client.html#oauth2Client-client-creds-grant"></a>Client Credentials</h3>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Please refer to the OAuth 2.0 Authorization Framework for further details on the <a href="https://tools.ietf.org/html/rfc6749#section-1.3.4">Client Credentials</a> grant.
</td>
</tr>
</table>
</div>
<div class="sect3">
<h4 id="_requesting_an_access_token_2"><a class="anchor" href="oauth2-client.html#_requesting_an_access_token_2"></a>Requesting an Access Token</h4>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Please refer to the <a href="https://tools.ietf.org/html/rfc6749#section-4.4.2">Access Token Request/Response</a> protocol flow for the Client Credentials grant.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The default implementation of <code>OAuth2AccessTokenResponseClient</code> for the Client Credentials grant is <code>DefaultClientCredentialsTokenResponseClient</code>, which uses a <code>RestOperations</code> when requesting an access token at the Authorization Server’s Token Endpoint.</p>
</div>
<div class="paragraph">
<p>The <code>DefaultClientCredentialsTokenResponseClient</code> is quite flexible as it allows you to customize the pre-processing of the Token Request and/or post-handling of the Token Response.</p>
</div>
</div>
<div class="sect3">
<h4 id="_customizing_the_access_token_request_3"><a class="anchor" href="oauth2-client.html#_customizing_the_access_token_request_3"></a>Customizing the Access Token Request</h4>
<div class="paragraph">
<p>If you need to customize the pre-processing of the Token Request, you can provide <code>DefaultClientCredentialsTokenResponseClient.setRequestEntityConverter()</code> with a custom <code>Converter&lt;OAuth2ClientCredentialsGrantRequest, RequestEntity&lt;?&gt;&gt;</code>.
The default implementation <code>OAuth2ClientCredentialsGrantRequestEntityConverter</code> builds a <code>RequestEntity</code> representation of a standard <a href="https://tools.ietf.org/html/rfc6749#section-4.4.2">OAuth 2.0 Access Token Request</a>.
However, providing a custom <code>Converter</code>, would allow you to extend the standard Token Request and add custom parameter(s).</p>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
The custom <code>Converter</code> must return a valid <code>RequestEntity</code> representation of an OAuth 2.0 Access Token Request that is understood by the intended OAuth 2.0 Provider.
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_customizing_the_access_token_response_3"><a class="anchor" href="oauth2-client.html#_customizing_the_access_token_response_3"></a>Customizing the Access Token Response</h4>
<div class="paragraph">
<p>On the other end, if you need to customize the post-handling of the Token Response, you will need to provide <code>DefaultClientCredentialsTokenResponseClient.setRestOperations()</code> with a custom configured <code>RestOperations</code>.
The default <code>RestOperations</code> is configured as follows:</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock primary">
<div class="title">Java</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">RestTemplate restTemplate = new RestTemplate(Arrays.asList(
		new FormHttpMessageConverter(),
		new OAuth2AccessTokenResponseHttpMessageConverter()));

restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Kotlin</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-kotlin hljs" data-lang="kotlin">val restTemplate = RestTemplate(listOf(
        FormHttpMessageConverter(),
        OAuth2AccessTokenResponseHttpMessageConverter()))

restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler()</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
Spring MVC <code>FormHttpMessageConverter</code> is required as it&#8217;s used when sending the OAuth 2.0 Access Token Request.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p><code>OAuth2AccessTokenResponseHttpMessageConverter</code> is a <code>HttpMessageConverter</code> for an OAuth 2.0 Access Token Response.
You can provide <code>OAuth2AccessTokenResponseHttpMessageConverter.setAccessTokenResponseConverter()</code> with a custom <code>Converter&lt;Map&lt;String, Object&gt;, OAuth2AccessTokenResponse&gt;</code> that is used for converting the OAuth 2.0 Access Token Response parameters to an <code>OAuth2AccessTokenResponse</code>.</p>
</div>
<div class="paragraph">
<p><code>OAuth2ErrorResponseErrorHandler</code> is a <code>ResponseErrorHandler</code> that can handle an OAuth 2.0 Error, eg. 400 Bad Request.
It uses an <code>OAuth2ErrorHttpMessageConverter</code> for converting the OAuth 2.0 Error parameters to an <code>OAuth2Error</code>.</p>
</div>
<div class="paragraph">
<p>Whether you customize <code>DefaultClientCredentialsTokenResponseClient</code> or provide your own implementation of <code>OAuth2AccessTokenResponseClient</code>, you&#8217;ll need to configure it as shown in the following example:</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock primary">
<div class="title">Java</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">// Customize
OAuth2AccessTokenResponseClient&lt;OAuth2ClientCredentialsGrantRequest&gt; clientCredentialsTokenResponseClient = ...

OAuth2AuthorizedClientProvider authorizedClientProvider =
		OAuth2AuthorizedClientProviderBuilder.builder()
				.clientCredentials(configurer -&gt; configurer.accessTokenResponseClient(clientCredentialsTokenResponseClient))
				.build();

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Kotlin</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-kotlin hljs" data-lang="kotlin">// Customize
val clientCredentialsTokenResponseClient: OAuth2AccessTokenResponseClient&lt;OAuth2ClientCredentialsGrantRequest&gt; = ...

val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
        .clientCredentials { it.accessTokenResponseClient(clientCredentialsTokenResponseClient) }
        .build()

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<code>OAuth2AuthorizedClientProviderBuilder.builder().clientCredentials()</code> configures a <code>ClientCredentialsOAuth2AuthorizedClientProvider</code>,
which is an implementation of an <code>OAuth2AuthorizedClientProvider</code> for the Client Credentials grant.
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_using_the_access_token"><a class="anchor" href="oauth2-client.html#_using_the_access_token"></a>Using the Access Token</h4>
<div class="paragraph">
<p>Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">spring:
  security:
    oauth2:
      client:
        registration:
          okta:
            client-id: okta-client-id
            client-secret: okta-client-secret
            authorization-grant-type: client_credentials
            scope: read, write
        provider:
          okta:
            token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token</code></pre>
</div>
</div>
<div class="paragraph">
<p>&#8230;&#8203;and the <code>OAuth2AuthorizedClientManager</code> <code>@Bean</code>:</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock primary">
<div class="title">Java</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Bean
public OAuth2AuthorizedClientManager authorizedClientManager(
		ClientRegistrationRepository clientRegistrationRepository,
		OAuth2AuthorizedClientRepository authorizedClientRepository) {

	OAuth2AuthorizedClientProvider authorizedClientProvider =
			OAuth2AuthorizedClientProviderBuilder.builder()
					.clientCredentials()
					.build();

	DefaultOAuth2AuthorizedClientManager authorizedClientManager =
			new DefaultOAuth2AuthorizedClientManager(
					clientRegistrationRepository, authorizedClientRepository);
	authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

	return authorizedClientManager;
}</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Kotlin</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-kotlin hljs" data-lang="kotlin">@Bean
fun authorizedClientManager(
        clientRegistrationRepository: ClientRegistrationRepository,
        authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager {
    val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
            .clientCredentials()
            .build()
    val authorizedClientManager = DefaultOAuth2AuthorizedClientManager(
            clientRegistrationRepository, authorizedClientRepository)
    authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
    return authorizedClientManager
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>You may obtain the <code>OAuth2AccessToken</code> as follows:</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock primary">
<div class="title">Java</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Controller
public class OAuth2ClientController {

	@Autowired
	private OAuth2AuthorizedClientManager authorizedClientManager;

	@GetMapping("/")
	public String index(Authentication authentication,
						HttpServletRequest servletRequest,
						HttpServletResponse servletResponse) {

		OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
				.principal(authentication)
				.attributes(attrs -&gt; {
					attrs.put(HttpServletRequest.class.getName(), servletRequest);
					attrs.put(HttpServletResponse.class.getName(), servletResponse);
				})
				.build();
		OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);

		OAuth2AccessToken accessToken = authorizedClient.getAccessToken();

		...

		return "index";
	}
}</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Kotlin</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-kotlin hljs" data-lang="kotlin">class OAuth2ClientController {

    @Autowired
    private lateinit var authorizedClientManager: OAuth2AuthorizedClientManager

    @GetMapping("/")
    fun index(authentication: Authentication?,
              servletRequest: HttpServletRequest,
              servletResponse: HttpServletResponse): String {
        val authorizeRequest: OAuth2AuthorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
                .principal(authentication)
                .attributes(Consumer { attrs: MutableMap&lt;String, Any&gt; -&gt;
                    attrs[HttpServletRequest::class.java.name] = servletRequest
                    attrs[HttpServletResponse::class.java.name] = servletResponse
                })
                .build()
        val authorizedClient = authorizedClientManager.authorize(authorizeRequest)
        val accessToken: OAuth2AccessToken = authorizedClient.accessToken

        ...

        return "index"
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<code>HttpServletRequest</code> and <code>HttpServletResponse</code> are both OPTIONAL attributes.
If not provided, it will default to <code>ServletRequestAttributes</code> using <code>RequestContextHolder.getRequestAttributes()</code>.
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="sect2">
<h3 id="oauth2Client-password-grant"><a class="anchor" href="oauth2-client.html#oauth2Client-password-grant"></a>Resource Owner Password Credentials</h3>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Please refer to the OAuth 2.0 Authorization Framework for further details on the <a href="https://tools.ietf.org/html/rfc6749#section-1.3.3">Resource Owner Password Credentials</a> grant.
</td>
</tr>
</table>
</div>
<div class="sect3">
<h4 id="_requesting_an_access_token_3"><a class="anchor" href="oauth2-client.html#_requesting_an_access_token_3"></a>Requesting an Access Token</h4>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Please refer to the <a href="https://tools.ietf.org/html/rfc6749#section-4.3.2">Access Token Request/Response</a> protocol flow for the Resource Owner Password Credentials grant.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The default implementation of <code>OAuth2AccessTokenResponseClient</code> for the Resource Owner Password Credentials grant is <code>DefaultPasswordTokenResponseClient</code>, which uses a <code>RestOperations</code> when requesting an access token at the Authorization Server’s Token Endpoint.</p>
</div>
<div class="paragraph">
<p>The <code>DefaultPasswordTokenResponseClient</code> is quite flexible as it allows you to customize the pre-processing of the Token Request and/or post-handling of the Token Response.</p>
</div>
</div>
<div class="sect3">
<h4 id="_customizing_the_access_token_request_4"><a class="anchor" href="oauth2-client.html#_customizing_the_access_token_request_4"></a>Customizing the Access Token Request</h4>
<div class="paragraph">
<p>If you need to customize the pre-processing of the Token Request, you can provide <code>DefaultPasswordTokenResponseClient.setRequestEntityConverter()</code> with a custom <code>Converter&lt;OAuth2PasswordGrantRequest, RequestEntity&lt;?&gt;&gt;</code>.
The default implementation <code>OAuth2PasswordGrantRequestEntityConverter</code> builds a <code>RequestEntity</code> representation of a standard <a href="https://tools.ietf.org/html/rfc6749#section-4.3.2">OAuth 2.0 Access Token Request</a>.
However, providing a custom <code>Converter</code>, would allow you to extend the standard Token Request and add custom parameter(s).</p>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
The custom <code>Converter</code> must return a valid <code>RequestEntity</code> representation of an OAuth 2.0 Access Token Request that is understood by the intended OAuth 2.0 Provider.
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_customizing_the_access_token_response_4"><a class="anchor" href="oauth2-client.html#_customizing_the_access_token_response_4"></a>Customizing the Access Token Response</h4>
<div class="paragraph">
<p>On the other end, if you need to customize the post-handling of the Token Response, you will need to provide <code>DefaultPasswordTokenResponseClient.setRestOperations()</code> with a custom configured <code>RestOperations</code>.
The default <code>RestOperations</code> is configured as follows:</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock primary">
<div class="title">Java</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">RestTemplate restTemplate = new RestTemplate(Arrays.asList(
		new FormHttpMessageConverter(),
		new OAuth2AccessTokenResponseHttpMessageConverter()));

restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Kotlin</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-kotlin hljs" data-lang="kotlin">val restTemplate = RestTemplate(listOf(
        FormHttpMessageConverter(),
        OAuth2AccessTokenResponseHttpMessageConverter()))

restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler()</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
Spring MVC <code>FormHttpMessageConverter</code> is required as it&#8217;s used when sending the OAuth 2.0 Access Token Request.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p><code>OAuth2AccessTokenResponseHttpMessageConverter</code> is a <code>HttpMessageConverter</code> for an OAuth 2.0 Access Token Response.
You can provide <code>OAuth2AccessTokenResponseHttpMessageConverter.setAccessTokenResponseConverter()</code> with a custom <code>Converter&lt;Map&lt;String, Object&gt;, OAuth2AccessTokenResponse&gt;</code> that is used for converting the OAuth 2.0 Access Token Response parameters to an <code>OAuth2AccessTokenResponse</code>.</p>
</div>
<div class="paragraph">
<p><code>OAuth2ErrorResponseErrorHandler</code> is a <code>ResponseErrorHandler</code> that can handle an OAuth 2.0 Error, eg. 400 Bad Request.
It uses an <code>OAuth2ErrorHttpMessageConverter</code> for converting the OAuth 2.0 Error parameters to an <code>OAuth2Error</code>.</p>
</div>
<div class="paragraph">
<p>Whether you customize <code>DefaultPasswordTokenResponseClient</code> or provide your own implementation of <code>OAuth2AccessTokenResponseClient</code>, you&#8217;ll need to configure it as shown in the following example:</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock primary">
<div class="title">Java</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">// Customize
OAuth2AccessTokenResponseClient&lt;OAuth2PasswordGrantRequest&gt; passwordTokenResponseClient = ...

OAuth2AuthorizedClientProvider authorizedClientProvider =
		OAuth2AuthorizedClientProviderBuilder.builder()
				.password(configurer -&gt; configurer.accessTokenResponseClient(passwordTokenResponseClient))
				.refreshToken()
				.build();

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Kotlin</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-kotlin hljs" data-lang="kotlin">val passwordTokenResponseClient: OAuth2AccessTokenResponseClient&lt;OAuth2PasswordGrantRequest&gt; = ...

val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
        .password { it.accessTokenResponseClient(passwordTokenResponseClient) }
        .refreshToken()
        .build()

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<code>OAuth2AuthorizedClientProviderBuilder.builder().password()</code> configures a <code>PasswordOAuth2AuthorizedClientProvider</code>,
which is an implementation of an <code>OAuth2AuthorizedClientProvider</code> for the Resource Owner Password Credentials grant.
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_using_the_access_token_2"><a class="anchor" href="oauth2-client.html#_using_the_access_token_2"></a>Using the Access Token</h4>
<div class="paragraph">
<p>Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">spring:
  security:
    oauth2:
      client:
        registration:
          okta:
            client-id: okta-client-id
            client-secret: okta-client-secret
            authorization-grant-type: password
            scope: read, write
        provider:
          okta:
            token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token</code></pre>
</div>
</div>
<div class="paragraph">
<p>&#8230;&#8203;and the <code>OAuth2AuthorizedClientManager</code> <code>@Bean</code>:</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock primary">
<div class="title">Java</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Bean
public OAuth2AuthorizedClientManager authorizedClientManager(
		ClientRegistrationRepository clientRegistrationRepository,
		OAuth2AuthorizedClientRepository authorizedClientRepository) {

	OAuth2AuthorizedClientProvider authorizedClientProvider =
			OAuth2AuthorizedClientProviderBuilder.builder()
					.password()
					.refreshToken()
					.build();

	DefaultOAuth2AuthorizedClientManager authorizedClientManager =
			new DefaultOAuth2AuthorizedClientManager(
					clientRegistrationRepository, authorizedClientRepository);
	authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

	// Assuming the `username` and `password` are supplied as `HttpServletRequest` parameters,
	// map the `HttpServletRequest` parameters to `OAuth2AuthorizationContext.getAttributes()`
	authorizedClientManager.setContextAttributesMapper(contextAttributesMapper());

	return authorizedClientManager;
}

private Function&lt;OAuth2AuthorizeRequest, Map&lt;String, Object&gt;&gt; contextAttributesMapper() {
	return authorizeRequest -&gt; {
		Map&lt;String, Object&gt; contextAttributes = Collections.emptyMap();
		HttpServletRequest servletRequest = authorizeRequest.getAttribute(HttpServletRequest.class.getName());
		String username = servletRequest.getParameter(OAuth2ParameterNames.USERNAME);
		String password = servletRequest.getParameter(OAuth2ParameterNames.PASSWORD);
		if (StringUtils.hasText(username) &amp;&amp; StringUtils.hasText(password)) {
			contextAttributes = new HashMap&lt;&gt;();

			// `PasswordOAuth2AuthorizedClientProvider` requires both attributes
			contextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username);
			contextAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password);
		}
		return contextAttributes;
	};
}</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Kotlin</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-kotlin hljs" data-lang="kotlin">@Bean
fun authorizedClientManager(
        clientRegistrationRepository: ClientRegistrationRepository,
        authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager {
    val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
            .password()
            .refreshToken()
            .build()
    val authorizedClientManager = DefaultOAuth2AuthorizedClientManager(
            clientRegistrationRepository, authorizedClientRepository)
    authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)

    // Assuming the `username` and `password` are supplied as `HttpServletRequest` parameters,
    // map the `HttpServletRequest` parameters to `OAuth2AuthorizationContext.getAttributes()`
    authorizedClientManager.setContextAttributesMapper(contextAttributesMapper())
    return authorizedClientManager
}

private fun contextAttributesMapper(): Function&lt;OAuth2AuthorizeRequest, MutableMap&lt;String, Any&gt;&gt; {
    return Function { authorizeRequest -&gt;
        var contextAttributes: MutableMap&lt;String, Any&gt; = mutableMapOf()
        val servletRequest: HttpServletRequest = authorizeRequest.getAttribute(HttpServletRequest::class.java.name)
        val username = servletRequest.getParameter(OAuth2ParameterNames.USERNAME)
        val password = servletRequest.getParameter(OAuth2ParameterNames.PASSWORD)
        if (StringUtils.hasText(username) &amp;&amp; StringUtils.hasText(password)) {
            contextAttributes = hashMapOf()

            // `PasswordOAuth2AuthorizedClientProvider` requires both attributes
            contextAttributes[OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME] = username
            contextAttributes[OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME] = password
        }
        contextAttributes
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>You may obtain the <code>OAuth2AccessToken</code> as follows:</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock primary">
<div class="title">Java</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Controller
public class OAuth2ClientController {

	@Autowired
	private OAuth2AuthorizedClientManager authorizedClientManager;

	@GetMapping("/")
	public String index(Authentication authentication,
						HttpServletRequest servletRequest,
						HttpServletResponse servletResponse) {

		OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
				.principal(authentication)
				.attributes(attrs -&gt; {
					attrs.put(HttpServletRequest.class.getName(), servletRequest);
					attrs.put(HttpServletResponse.class.getName(), servletResponse);
				})
				.build();
		OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);

		OAuth2AccessToken accessToken = authorizedClient.getAccessToken();

		...

		return "index";
	}
}</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Kotlin</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-kotlin hljs" data-lang="kotlin">@Controller
class OAuth2ClientController {
    @Autowired
    private lateinit var authorizedClientManager: OAuth2AuthorizedClientManager

    @GetMapping("/")
    fun index(authentication: Authentication?,
              servletRequest: HttpServletRequest,
              servletResponse: HttpServletResponse): String {
        val authorizeRequest: OAuth2AuthorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
                .principal(authentication)
                .attributes(Consumer {
                    it[HttpServletRequest::class.java.name] = servletRequest
                    it[HttpServletResponse::class.java.name] = servletResponse
                })
                .build()
        val authorizedClient = authorizedClientManager.authorize(authorizeRequest)
        val accessToken: OAuth2AccessToken = authorizedClient.accessToken

        ...

        return "index"
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<code>HttpServletRequest</code> and <code>HttpServletResponse</code> are both OPTIONAL attributes.
If not provided, it will default to <code>ServletRequestAttributes</code> using <code>RequestContextHolder.getRequestAttributes()</code>.
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="sect2">
<h3 id="oauth2Client-jwt-bearer-grant"><a class="anchor" href="oauth2-client.html#oauth2Client-jwt-bearer-grant"></a>JWT Bearer</h3>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Please refer to JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication and Authorization Grants for further details on the <a href="https://datatracker.ietf.org/doc/html/rfc7523">JWT Bearer</a> grant.
</td>
</tr>
</table>
</div>
<div class="sect3">
<h4 id="_requesting_an_access_token_4"><a class="anchor" href="oauth2-client.html#_requesting_an_access_token_4"></a>Requesting an Access Token</h4>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Please refer to the <a href="https://datatracker.ietf.org/doc/html/rfc7523#section-2.1">Access Token Request/Response</a> protocol flow for the JWT Bearer grant.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The default implementation of <code>OAuth2AccessTokenResponseClient</code> for the JWT Bearer grant is <code>DefaultJwtBearerTokenResponseClient</code>, which uses a <code>RestOperations</code> when requesting an access token at the Authorization Server’s Token Endpoint.</p>
</div>
<div class="paragraph">
<p>The <code>DefaultJwtBearerTokenResponseClient</code> is quite flexible as it allows you to customize the pre-processing of the Token Request and/or post-handling of the Token Response.</p>
</div>
</div>
<div class="sect3">
<h4 id="_customizing_the_access_token_request_5"><a class="anchor" href="oauth2-client.html#_customizing_the_access_token_request_5"></a>Customizing the Access Token Request</h4>
<div class="paragraph">
<p>If you need to customize the pre-processing of the Token Request, you can provide <code>DefaultJwtBearerTokenResponseClient.setRequestEntityConverter()</code> with a custom <code>Converter&lt;JwtBearerGrantRequest, RequestEntity&lt;?&gt;&gt;</code>.
The default implementation <code>JwtBearerGrantRequestEntityConverter</code> builds a <code>RequestEntity</code> representation of a <a href="https://datatracker.ietf.org/doc/html/rfc7523#section-2.1">OAuth 2.0 Access Token Request</a>.
However, providing a custom <code>Converter</code>, would allow you to extend the Token Request and add custom parameter(s).</p>
</div>
</div>
<div class="sect3">
<h4 id="_customizing_the_access_token_response_5"><a class="anchor" href="oauth2-client.html#_customizing_the_access_token_response_5"></a>Customizing the Access Token Response</h4>
<div class="paragraph">
<p>On the other end, if you need to customize the post-handling of the Token Response, you will need to provide <code>DefaultJwtBearerTokenResponseClient.setRestOperations()</code> with a custom configured <code>RestOperations</code>.
The default <code>RestOperations</code> is configured as follows:</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock primary">
<div class="title">Java</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">RestTemplate restTemplate = new RestTemplate(Arrays.asList(
		new FormHttpMessageConverter(),
		new OAuth2AccessTokenResponseHttpMessageConverter()));

restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Kotlin</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-kotlin hljs" data-lang="kotlin">val restTemplate = RestTemplate(listOf(
        FormHttpMessageConverter(),
        OAuth2AccessTokenResponseHttpMessageConverter()))

restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler()</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
Spring MVC <code>FormHttpMessageConverter</code> is required as it&#8217;s used when sending the OAuth 2.0 Access Token Request.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p><code>OAuth2AccessTokenResponseHttpMessageConverter</code> is a <code>HttpMessageConverter</code> for an OAuth 2.0 Access Token Response.
You can provide <code>OAuth2AccessTokenResponseHttpMessageConverter.setAccessTokenResponseConverter()</code> with a custom <code>Converter&lt;Map&lt;String, Object&gt;, OAuth2AccessTokenResponse&gt;</code> that is used for converting the OAuth 2.0 Access Token Response parameters to an <code>OAuth2AccessTokenResponse</code>.</p>
</div>
<div class="paragraph">
<p><code>OAuth2ErrorResponseErrorHandler</code> is a <code>ResponseErrorHandler</code> that can handle an OAuth 2.0 Error, eg. 400 Bad Request.
It uses an <code>OAuth2ErrorHttpMessageConverter</code> for converting the OAuth 2.0 Error parameters to an <code>OAuth2Error</code>.</p>
</div>
<div class="paragraph">
<p>Whether you customize <code>DefaultJwtBearerTokenResponseClient</code> or provide your own implementation of <code>OAuth2AccessTokenResponseClient</code>, you&#8217;ll need to configure it as shown in the following example:</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock primary">
<div class="title">Java</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">// Customize
OAuth2AccessTokenResponseClient&lt;JwtBearerGrantRequest&gt; jwtBearerTokenResponseClient = ...

JwtBearerOAuth2AuthorizedClientProvider jwtBearerAuthorizedClientProvider = new JwtBearerOAuth2AuthorizedClientProvider();
jwtBearerAuthorizedClientProvider.setAccessTokenResponseClient(jwtBearerTokenResponseClient);

OAuth2AuthorizedClientProvider authorizedClientProvider =
		OAuth2AuthorizedClientProviderBuilder.builder()
				.provider(jwtBearerAuthorizedClientProvider)
				.build();

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Kotlin</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-kotlin hljs" data-lang="kotlin">// Customize
val jwtBearerTokenResponseClient: OAuth2AccessTokenResponseClient&lt;JwtBearerGrantRequest&gt; = ...

val jwtBearerAuthorizedClientProvider = JwtBearerOAuth2AuthorizedClientProvider()
jwtBearerAuthorizedClientProvider.setAccessTokenResponseClient(jwtBearerTokenResponseClient);

val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
        .provider(jwtBearerAuthorizedClientProvider)
        .build()

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_using_the_access_token_3"><a class="anchor" href="oauth2-client.html#_using_the_access_token_3"></a>Using the Access Token</h4>
<div class="paragraph">
<p>Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">spring:
  security:
    oauth2:
      client:
        registration:
          okta:
            client-id: okta-client-id
            client-secret: okta-client-secret
            authorization-grant-type: urn:ietf:params:oauth:grant-type:jwt-bearer
            scope: read
        provider:
          okta:
            token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token</code></pre>
</div>
</div>
<div class="paragraph">
<p>&#8230;&#8203;and the <code>OAuth2AuthorizedClientManager</code> <code>@Bean</code>:</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock primary">
<div class="title">Java</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Bean
public OAuth2AuthorizedClientManager authorizedClientManager(
		ClientRegistrationRepository clientRegistrationRepository,
		OAuth2AuthorizedClientRepository authorizedClientRepository) {

	JwtBearerOAuth2AuthorizedClientProvider jwtBearerAuthorizedClientProvider =
			new JwtBearerOAuth2AuthorizedClientProvider();

	OAuth2AuthorizedClientProvider authorizedClientProvider =
			OAuth2AuthorizedClientProviderBuilder.builder()
					.provider(jwtBearerAuthorizedClientProvider)
					.build();

	DefaultOAuth2AuthorizedClientManager authorizedClientManager =
			new DefaultOAuth2AuthorizedClientManager(
					clientRegistrationRepository, authorizedClientRepository);
	authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

	return authorizedClientManager;
}</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Kotlin</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-kotlin hljs" data-lang="kotlin">@Bean
fun authorizedClientManager(
        clientRegistrationRepository: ClientRegistrationRepository,
        authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager {
    val jwtBearerAuthorizedClientProvider = JwtBearerOAuth2AuthorizedClientProvider()
    val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
            .provider(jwtBearerAuthorizedClientProvider)
            .build()
    val authorizedClientManager = DefaultOAuth2AuthorizedClientManager(
            clientRegistrationRepository, authorizedClientRepository)
    authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
    return authorizedClientManager
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>You may obtain the <code>OAuth2AccessToken</code> as follows:</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock primary">
<div class="title">Java</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@RestController
public class OAuth2ResourceServerController {

	@Autowired
	private OAuth2AuthorizedClientManager authorizedClientManager;

	@GetMapping("/resource")
	public String resource(JwtAuthenticationToken jwtAuthentication) {
		OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
				.principal(jwtAuthentication)
				.build();
		OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);
		OAuth2AccessToken accessToken = authorizedClient.getAccessToken();

		...

	}
}</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Kotlin</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-kotlin hljs" data-lang="kotlin">class OAuth2ResourceServerController {

    @Autowired
    private lateinit var authorizedClientManager: OAuth2AuthorizedClientManager

    @GetMapping("/resource")
    fun resource(jwtAuthentication: JwtAuthenticationToken?): String {
        val authorizeRequest: OAuth2AuthorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
                .principal(jwtAuthentication)
                .build()
        val authorizedClient = authorizedClientManager.authorize(authorizeRequest)
        val accessToken: OAuth2AccessToken = authorizedClient.accessToken

        ...

    }
}</code></pre>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="oauth2Client-client-auth-support"><a class="anchor" href="oauth2-client.html#oauth2Client-client-auth-support"></a>Client Authentication Support</h2>
<div class="sectionbody">
<div class="sect2">
<h3 id="oauth2Client-jwt-bearer-auth"><a class="anchor" href="oauth2-client.html#oauth2Client-jwt-bearer-auth"></a>JWT Bearer</h3>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Please refer to JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication and Authorization Grants for further details on <a href="https://datatracker.ietf.org/doc/html/rfc7523#section-2.2">JWT Bearer</a> Client Authentication.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The default implementation for JWT Bearer Client Authentication is <code>NimbusJwtClientAuthenticationParametersConverter</code>,
which is a <code>Converter</code> that customizes the Token Request parameters by adding
a signed JSON Web Token (JWS) in the <code>client_assertion</code> parameter.</p>
</div>
<div class="paragraph">
<p>The <code>java.security.PrivateKey</code> or <code>javax.crypto.SecretKey</code> used for signing the JWS
is supplied by the <code>com.nimbusds.jose.jwk.JWK</code> resolver associated with <code>NimbusJwtClientAuthenticationParametersConverter</code>.</p>
</div>
<div class="sect3">
<h4 id="_authenticate_using_private_key_jwt"><a class="anchor" href="oauth2-client.html#_authenticate_using_private_key_jwt"></a>Authenticate using <code>private_key_jwt</code></h4>
<div class="paragraph">
<p>Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">spring:
  security:
    oauth2:
      client:
        registration:
          okta:
            client-id: okta-client-id
            client-authentication-method: private_key_jwt
            authorization-grant-type: authorization_code
            ...</code></pre>
</div>
</div>
<div class="paragraph">
<p>The following example shows how to configure <code>DefaultAuthorizationCodeTokenResponseClient</code>:</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock primary">
<div class="title">Java</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">Function&lt;ClientRegistration, JWK&gt; jwkResolver = (clientRegistration) -&gt; {
	if (clientRegistration.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.PRIVATE_KEY_JWT)) {
		// Assuming RSA key type
		RSAPublicKey publicKey = ...
		RSAPrivateKey privateKey = ...
		return new RSAKey.Builder(publicKey)
				.privateKey(privateKey)
				.keyID(UUID.randomUUID().toString())
				.build();
	}
	return null;
};

OAuth2AuthorizationCodeGrantRequestEntityConverter requestEntityConverter =
		new OAuth2AuthorizationCodeGrantRequestEntityConverter();
requestEntityConverter.addParametersConverter(
		new NimbusJwtClientAuthenticationParametersConverter&lt;&gt;(jwkResolver));

DefaultAuthorizationCodeTokenResponseClient tokenResponseClient =
		new DefaultAuthorizationCodeTokenResponseClient();
tokenResponseClient.setRequestEntityConverter(requestEntityConverter);</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Kotlin</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-kotlin hljs" data-lang="kotlin">val jwkResolver: Function&lt;ClientRegistration, JWK&gt; =
    Function&lt;ClientRegistration, JWK&gt; { clientRegistration -&gt;
        if (clientRegistration.clientAuthenticationMethod.equals(ClientAuthenticationMethod.PRIVATE_KEY_JWT)) {
            // Assuming RSA key type
            var publicKey: RSAPublicKey
            var privateKey: RSAPrivateKey
            RSAKey.Builder(publicKey) = //...
                .privateKey(privateKey) = //...
                .keyID(UUID.randomUUID().toString())
                .build()
        }
        null
    }

val requestEntityConverter = OAuth2AuthorizationCodeGrantRequestEntityConverter()
requestEntityConverter.addParametersConverter(
    NimbusJwtClientAuthenticationParametersConverter(jwkResolver)
)

val tokenResponseClient = DefaultAuthorizationCodeTokenResponseClient()
tokenResponseClient.setRequestEntityConverter(requestEntityConverter)</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_authenticate_using_client_secret_jwt"><a class="anchor" href="oauth2-client.html#_authenticate_using_client_secret_jwt"></a>Authenticate using <code>client_secret_jwt</code></h4>
<div class="paragraph">
<p>Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">spring:
  security:
    oauth2:
      client:
        registration:
          okta:
            client-id: okta-client-id
            client-secret: okta-client-secret
            client-authentication-method: client_secret_jwt
            authorization-grant-type: client_credentials
            ...</code></pre>
</div>
</div>
<div class="paragraph">
<p>The following example shows how to configure <code>DefaultClientCredentialsTokenResponseClient</code>:</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock primary">
<div class="title">Java</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">Function&lt;ClientRegistration, JWK&gt; jwkResolver = (clientRegistration) -&gt; {
	if (clientRegistration.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.CLIENT_SECRET_JWT)) {
		SecretKeySpec secretKey = new SecretKeySpec(
				clientRegistration.getClientSecret().getBytes(StandardCharsets.UTF_8),
				"HmacSHA256");
		return new OctetSequenceKey.Builder(secretKey)
				.keyID(UUID.randomUUID().toString())
				.build();
	}
	return null;
};

OAuth2ClientCredentialsGrantRequestEntityConverter requestEntityConverter =
		new OAuth2ClientCredentialsGrantRequestEntityConverter();
requestEntityConverter.addParametersConverter(
		new NimbusJwtClientAuthenticationParametersConverter&lt;&gt;(jwkResolver));

DefaultClientCredentialsTokenResponseClient tokenResponseClient =
		new DefaultClientCredentialsTokenResponseClient();
tokenResponseClient.setRequestEntityConverter(requestEntityConverter);</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Kotlin</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-kotlin hljs" data-lang="kotlin">val jwkResolver = Function&lt;ClientRegistration, JWK?&gt; { clientRegistration: ClientRegistration -&gt;
    if (clientRegistration.clientAuthenticationMethod == ClientAuthenticationMethod.CLIENT_SECRET_JWT) {
        val secretKey = SecretKeySpec(
            clientRegistration.clientSecret.toByteArray(StandardCharsets.UTF_8),
            "HmacSHA256"
        )
        OctetSequenceKey.Builder(secretKey)
            .keyID(UUID.randomUUID().toString())
            .build()
    }
    null
}

val requestEntityConverter = OAuth2ClientCredentialsGrantRequestEntityConverter()
requestEntityConverter.addParametersConverter(
    NimbusJwtClientAuthenticationParametersConverter(jwkResolver)
)

val tokenResponseClient = DefaultClientCredentialsTokenResponseClient()
tokenResponseClient.setRequestEntityConverter(requestEntityConverter)</code></pre>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="oauth2Client-additional-features"><a class="anchor" href="oauth2-client.html#oauth2Client-additional-features"></a>Additional Features</h2>
<div class="sectionbody">
<div class="sect2">
<h3 id="oauth2Client-registered-authorized-client"><a class="anchor" href="oauth2-client.html#oauth2Client-registered-authorized-client"></a>Resolving an Authorized Client</h3>
<div class="paragraph">
<p>The <code>@RegisteredOAuth2AuthorizedClient</code> annotation provides the capability of resolving a method parameter to an argument value of type <code>OAuth2AuthorizedClient</code>.
This is a convenient alternative compared to accessing the <code>OAuth2AuthorizedClient</code> using the <code>OAuth2AuthorizedClientManager</code> or <code>OAuth2AuthorizedClientService</code>.</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock primary">
<div class="title">Java</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Controller
public class OAuth2ClientController {

	@GetMapping("/")
	public String index(@RegisteredOAuth2AuthorizedClient("okta") OAuth2AuthorizedClient authorizedClient) {
		OAuth2AccessToken accessToken = authorizedClient.getAccessToken();

		...

		return "index";
	}
}</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Kotlin</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-kotlin hljs" data-lang="kotlin">@Controller
class OAuth2ClientController {
    @GetMapping("/")
    fun index(@RegisteredOAuth2AuthorizedClient("okta") authorizedClient: OAuth2AuthorizedClient): String {
        val accessToken = authorizedClient.accessToken

        ...

        return "index"
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>The <code>@RegisteredOAuth2AuthorizedClient</code> annotation is handled by <code>OAuth2AuthorizedClientArgumentResolver</code>, which directly uses an <a href="oauth2-client.html#oauth2Client-authorized-manager-provider">OAuth2AuthorizedClientManager</a> and therefore inherits it&#8217;s capabilities.</p>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="oauth2Client-webclient-servlet"><a class="anchor" href="oauth2-client.html#oauth2Client-webclient-servlet"></a>WebClient integration for Servlet Environments</h2>
<div class="sectionbody">
<div class="paragraph">
<p>The OAuth 2.0 Client support integrates with <code>WebClient</code> using an <code>ExchangeFilterFunction</code>.</p>
</div>
<div class="paragraph">
<p>The <code>ServletOAuth2AuthorizedClientExchangeFilterFunction</code> provides a simple mechanism for requesting protected resources by using an <code>OAuth2AuthorizedClient</code> and including the associated <code>OAuth2AccessToken</code> as a Bearer Token.
It directly uses an <a href="oauth2-client.html#oauth2Client-authorized-manager-provider">OAuth2AuthorizedClientManager</a> and therefore inherits the following capabilities:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>An <code>OAuth2AccessToken</code> will be requested if the client has not yet been authorized.</p>
<div class="ulist">
<ul>
<li>
<p><code>authorization_code</code> - triggers the Authorization Request redirect to initiate the flow</p>
</li>
<li>
<p><code>client_credentials</code> - the access token is obtained directly from the Token Endpoint</p>
</li>
<li>
<p><code>password</code> - the access token is obtained directly from the Token Endpoint</p>
</li>
</ul>
</div>
</li>
<li>
<p>If the <code>OAuth2AccessToken</code> is expired, it will be refreshed (or renewed) if an <code>OAuth2AuthorizedClientProvider</code> is available to perform the authorization</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>The following code shows an example of how to configure <code>WebClient</code> with OAuth 2.0 Client support:</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock primary">
<div class="title">Java</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Bean
WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) {
	ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client =
			new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
	return WebClient.builder()
			.apply(oauth2Client.oauth2Configuration())
			.build();
}</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Kotlin</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-kotlin hljs" data-lang="kotlin">@Bean
fun webClient(authorizedClientManager: OAuth2AuthorizedClientManager?): WebClient {
    val oauth2Client = ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager)
    return WebClient.builder()
            .apply(oauth2Client.oauth2Configuration())
            .build()
}</code></pre>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_providing_the_authorized_client"><a class="anchor" href="oauth2-client.html#_providing_the_authorized_client"></a>Providing the Authorized Client</h3>
<div class="paragraph">
<p>The <code>ServletOAuth2AuthorizedClientExchangeFilterFunction</code> determines the client to use (for a request) by resolving the <code>OAuth2AuthorizedClient</code> from the <code>ClientRequest.attributes()</code> (request attributes).</p>
</div>
<div class="paragraph">
<p>The following code shows how to set an <code>OAuth2AuthorizedClient</code> as a request attribute:</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock primary">
<div class="title">Java</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@GetMapping("/")
public String index(@RegisteredOAuth2AuthorizedClient("okta") OAuth2AuthorizedClient authorizedClient) {
	String resourceUri = ...

	String body = webClient
			.get()
			.uri(resourceUri)
			.attributes(oauth2AuthorizedClient(authorizedClient))   <i class="conum" data-value="1"></i><b>(1)</b>
			.retrieve()
			.bodyToMono(String.class)
			.block();

	...

	return "index";
}</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Kotlin</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-kotlin hljs" data-lang="kotlin">@GetMapping("/")
fun index(@RegisteredOAuth2AuthorizedClient("okta") authorizedClient: OAuth2AuthorizedClient): String {
    val resourceUri: String = ...
    val body: String = webClient
            .get()
            .uri(resourceUri)
            .attributes(oauth2AuthorizedClient(authorizedClient)) <i class="conum" data-value="1"></i><b>(1)</b>
            .retrieve()
            .bodyToMono()
            .block()

    ...

    return "index"
}</code></pre>
</div>
</div>
</div>
</div>
<div class="colist arabic">
<table>
<tr>
<td><i class="conum" data-value="1"></i><b>1</b></td>
<td><code>oauth2AuthorizedClient()</code> is a <code>static</code> method in <code>ServletOAuth2AuthorizedClientExchangeFilterFunction</code>.</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The following code shows how to set the <code>ClientRegistration.getRegistrationId()</code> as a request attribute:</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock primary">
<div class="title">Java</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@GetMapping("/")
public String index() {
	String resourceUri = ...

	String body = webClient
			.get()
			.uri(resourceUri)
			.attributes(clientRegistrationId("okta"))   <i class="conum" data-value="1"></i><b>(1)</b>
			.retrieve()
			.bodyToMono(String.class)
			.block();

	...

	return "index";
}</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Kotlin</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-kotlin hljs" data-lang="kotlin">@GetMapping("/")
fun index(): String {
    val resourceUri: String = ...

    val body: String = webClient
            .get()
            .uri(resourceUri)
            .attributes(clientRegistrationId("okta"))  <i class="conum" data-value="1"></i><b>(1)</b>
            .retrieve()
            .bodyToMono()
            .block()

    ...

    return "index"
}</code></pre>
</div>
</div>
</div>
</div>
<div class="colist arabic">
<table>
<tr>
<td><i class="conum" data-value="1"></i><b>1</b></td>
<td><code>clientRegistrationId()</code> is a <code>static</code> method in <code>ServletOAuth2AuthorizedClientExchangeFilterFunction</code>.</td>
</tr>
</table>
</div>
</div>
<div class="sect2">
<h3 id="_defaulting_the_authorized_client"><a class="anchor" href="oauth2-client.html#_defaulting_the_authorized_client"></a>Defaulting the Authorized Client</h3>
<div class="paragraph">
<p>If neither <code>OAuth2AuthorizedClient</code> or <code>ClientRegistration.getRegistrationId()</code> is provided as a request attribute, the <code>ServletOAuth2AuthorizedClientExchangeFilterFunction</code> can determine the <em>default</em> client to use depending on it&#8217;s configuration.</p>
</div>
<div class="paragraph">
<p>If <code>setDefaultOAuth2AuthorizedClient(true)</code> is configured and the user has authenticated using <code>HttpSecurity.oauth2Login()</code>, the <code>OAuth2AccessToken</code> associated with the current <code>OAuth2AuthenticationToken</code> is used.</p>
</div>
<div class="paragraph">
<p>The following code shows the specific configuration:</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock primary">
<div class="title">Java</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Bean
WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) {
	ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client =
			new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
	oauth2Client.setDefaultOAuth2AuthorizedClient(true);
	return WebClient.builder()
			.apply(oauth2Client.oauth2Configuration())
			.build();
}</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Kotlin</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-kotlin hljs" data-lang="kotlin">@Bean
fun webClient(authorizedClientManager: OAuth2AuthorizedClientManager?): WebClient {
    val oauth2Client = ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager)
    oauth2Client.setDefaultOAuth2AuthorizedClient(true)
    return WebClient.builder()
            .apply(oauth2Client.oauth2Configuration())
            .build()
}</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<i class="fa icon-warning" title="Warning"></i>
</td>
<td class="content">
It is recommended to be cautious with this feature since all HTTP requests will receive the access token.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Alternatively, if <code>setDefaultClientRegistrationId("okta")</code> is configured with a valid <code>ClientRegistration</code>, the <code>OAuth2AccessToken</code> associated with the <code>OAuth2AuthorizedClient</code> is used.</p>
</div>
<div class="paragraph">
<p>The following code shows the specific configuration:</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock primary">
<div class="title">Java</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Bean
WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) {
	ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client =
			new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
	oauth2Client.setDefaultClientRegistrationId("okta");
	return WebClient.builder()
			.apply(oauth2Client.oauth2Configuration())
			.build();
}</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Kotlin</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-kotlin hljs" data-lang="kotlin">@Bean
fun webClient(authorizedClientManager: OAuth2AuthorizedClientManager?): WebClient {
    val oauth2Client = ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager)
    oauth2Client.setDefaultClientRegistrationId("okta")
    return WebClient.builder()
            .apply(oauth2Client.oauth2Configuration())
            .build()
}</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<i class="fa icon-warning" title="Warning"></i>
</td>
<td class="content">
It is recommended to be cautious with this feature since all HTTP requests will receive the access token.
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
<nav class="pagination">
<span class="prev"><a href="oauth2-login.html">OAuth2 Log In</a></span>
<span class="next"><a href="oauth2-resourceserver.html">OAuth2 Resource Server</a></span>
</nav>
</article>
</div>
</main>
</div>
<footer class="footer flex">
<div id="spring-links flex">
<img id="springlogo" src="../../../_/img/spring-logo.svg" alt="Spring">
<p class="smallest antialiased">© <script>var d = new Date();
        document.write(d.getFullYear());</script> <a href="https://www.vmware.com/">VMware</a>, Inc. or its affiliates. <a href="https://www.vmware.com/help/legal.html">Terms of Use</a> • <a href="https://www.vmware.com/help/privacy.html" rel="noopener noreferrer">Privacy</a> • <a href="https://spring.io/trademarks">Trademark Guidelines</a> <span id="thank-you-mobile">• <a href="https://spring.io/thank-you">Thank you</a></span> • <a href="https://www.vmware.com/help/privacy/california-privacy-rights.html">Your California Privacy Rights</a> • <a class="ot-sdk-show-settings">Cookie Settings</a> <span id="teconsent"></span></p>
<p class="smallest antialiased">Apache®, Apache Tomcat®, Apache Kafka®, Apache Cassandra&trade;, and Apache Geode&trade; are trademarks or registered trademarks of the Apache Software Foundation in the United States and/or other countries. Java&trade;, Java&trade; SE, Java&trade; EE, and OpenJDK&trade; are trademarks of Oracle and/or its affiliates. Kubernetes® is a registered trademark of the Linux Foundation in the United States and other countries. Linux® is the registered trademark of Linus Torvalds in the United States and other countries. Windows® and Microsoft® Azure are registered trademarks of Microsoft Corporation. “AWS” and “Amazon Web Services” are trademarks or registered trademarks of Amazon.com Inc. or its affiliates. All other trademarks and copyrights are property of their respective owners and are only mentioned for informative purposes. Other names may be trademarks of their respective owners.</p>
</div>
<div id="social-icons" class="flex jc-between">
<a href="https://www.youtube.com/user/SpringSourceDev" title="Youtube"><svg id="youtube-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40"><circle class="cls-1" cx="20" cy="20" r="20" /><path class="cls-2" d="M30.91,14.53a2.89,2.89,0,0,0-2-2C27.12,12,20,12,20,12s-7.12,0-8.9.47a2.9,2.9,0,0,0-2,2A30.56,30.56,0,0,0,8.63,20a30.44,30.44,0,0,0,.46,5.47,2.89,2.89,0,0,0,2,2C12.9,28,20,28,20,28s7.12,0,8.9-.47a2.87,2.87,0,0,0,2-2A30.56,30.56,0,0,0,31.37,20,28.88,28.88,0,0,0,30.91,14.53ZM17.73,23.41V16.59L23.65,20Z" /></svg></a>
<a href="https://github.com/spring-projects" title="Github"><svg id="github-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 75.93 75.93"><path class="cls-1" d="M38,0a38,38,0,1,0,38,38A38,38,0,0,0,38,0Z" /></g><path class="cls-2" d="M38,15.59A22.95,22.95,0,0,0,30.71,60.3c1.15.21,1.57-.5,1.57-1.11s0-2,0-3.9c-6.38,1.39-7.73-3.07-7.73-3.07A6.09,6.09,0,0,0,22,48.86c-2.09-1.42.15-1.39.15-1.39a4.81,4.81,0,0,1,3.52,2.36c2,3.5,5.37,2.49,6.67,1.91a4.87,4.87,0,0,1,1.46-3.07c-5.09-.58-10.45-2.55-10.45-11.34a8.84,8.84,0,0,1,2.36-6.15,8.29,8.29,0,0,1,.23-6.07s1.92-.62,6.3,2.35a21.82,21.82,0,0,1,11.49,0c4.38-3,6.3-2.35,6.3-2.35a8.29,8.29,0,0,1,.23,6.07,8.84,8.84,0,0,1,2.36,6.15c0,8.81-5.37,10.75-10.48,11.32a5.46,5.46,0,0,1,1.56,4.25c0,3.07,0,5.54,0,6.29s.42,1.33,1.58,1.1A22.94,22.94,0,0,0,38,15.59Z" /></svg></a>
<a href="https://twitter.com/springcentral" title="Twitter"><svg id="twitter-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 75.93 75.93"><circle class="cls-1" cx="37.97" cy="37.97" r="37.97" /><path id="Twitter-2" data-name="Twitter" class="cls-2" d="M55.2,22.73a15.43,15.43,0,0,1-4.88,1.91,7.56,7.56,0,0,0-5.61-2.49A7.78,7.78,0,0,0,37,30a7.56,7.56,0,0,0,.2,1.79,21.63,21.63,0,0,1-15.84-8.23,8,8,0,0,0,2.37,10.52,7.66,7.66,0,0,1-3.48-1v.09A7.84,7.84,0,0,0,26.45,41a7.54,7.54,0,0,1-2,.28A7.64,7.64,0,0,1,23,41.09a7.71,7.71,0,0,0,7.18,5.47,15.21,15.21,0,0,1-9.55,3.37,15.78,15.78,0,0,1-1.83-.11,21.41,21.41,0,0,0,11.78,3.54c14.13,0,21.86-12,21.86-22.42,0-.34,0-.68,0-1a15.67,15.67,0,0,0,3.83-4.08,14.9,14.9,0,0,1-4.41,1.24A7.8,7.8,0,0,0,55.2,22.73Z" /></svg></a>
</div>
</footer>
<script src="../../../_/js/site.js"></script>
<script async src="../../../_/js/vendor/highlight.js"></script>
<script async src="../../../_/js/vendor/tabs.js"></script>
<script src="../../../_/js/vendor/switchtheme.js"></script>
<script src="../../../_/js/vendor/docsearch.min.js"></script>

<script>
var search = docsearch({
  appId: '244V8V9FGG',
  apiKey: '82c7ead946afbac3cf98c32446154691',
  indexName: 'security-docs',
  inputSelector: '#search-input',
  autocompleteOptions: { hint: false, keyboardShortcuts: ['s'] },
  algoliaOptions: { hitsPerPage: 10 }
}).autocomplete
search.on('autocomplete:closed', function () { search.autocomplete.setVal() })
</script>
<script>if (window.parent == window) {(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,'script','//www.google-analytics.com/analytics.js','ga');ga('create', 'UA-2728886-23', 'auto', {'siteSpeedSampleRate': 100});ga('send', 'pageview');}</script><script defer src="https://static.cloudflareinsights.com/beacon.min.js/v652eace1692a40cfa3763df669d7439c1639079717194" integrity="sha512-Gi7xpJR8tSkrpF7aordPZQlW2DLtzUlZcumS8dMQjwDHEnw9I7ZLyiOj/6tZStRBGtGgN6ceN6cMH8z7etPGlw==" data-cf-beacon='{"rayId":"702e40585ea29830","token":"bffcb8a918ae4755926f76178bfbd26b","version":"2021.12.0","si":100}' crossorigin="anonymous"></script>
</body>
</html>
